python2 qt5 關(guān)于如何判斷字符串為空
問題描述
#!/usr/bin/python# -*- coding: UTF-8 -*-# QQ: 78619808# Created by Kylin on 2017/5/31import sysfrom PyQt5.QtWidgets import *class Window(QWidget): def __init__(self):super(Window,self).__init__()self.setWindowTitle(u’加密字符串’)self.setFixedSize(300,200)vbox=QVBoxLayout()self.inputbox=QTextEdit()vbox.addWidget(self.inputbox)hbox=QHBoxLayout()tranbtn=QPushButton(u’加密’)aboutbtn=QPushButton(u’關(guān)于’)self.resultLabel = QLabel('Result:')hbox.addWidget(aboutbtn)hbox.addWidget(tranbtn)aboutbtn.clicked.connect(self.OnAbout)tranbtn.clicked.connect(self.OnTran)vbox.addLayout(hbox)self.outputbox=QTextEdit()vbox.addWidget(self.outputbox)vbox.addWidget(self.resultLabel)self.setLayout(vbox) def OnAbout(self):QMessageBox.about(self,u’關(guān)于’,u’字符串加密工具 by 史艷文’) def OnTran(self):url = self.inputbox.toPlainText()if url.isEmpty(): #執(zhí)行到這里出錯了,退出了消息循環(huán) self.resultLabel.setText('是空的')self.resultLabel.setText('不是空的')if __name__==’__main__’: app=QApplication(sys.argv) myshow=Window() myshow.show() sys.exit(app.exec_())
pyqt4轉(zhuǎn)換到pyqt5后url.isEmpty()在pyqt4中這樣寫是沒問題,但是在pyqt5中出錯的(不會報錯,但是會退出消息循環(huán)) 該如何改?
問題解答
回答1:在PyQt4中,toPlainText方法返回的是QString類,QString類支持isEmpty方法。所以在PyQt4中這樣沒問題。而PyQt5大多數(shù)是在Python3下用的(當(dāng)然PyQt5+Python2也可以),在Python3中基本str類已經(jīng)很好的支持了各類字符編碼,所以PyQt5中已經(jīng)沒有QString了,所有期待QString類型的API,直接使用原生str即可。同樣的,toPlainText方法返回的也是原生的str類型。str沒有isEmpty方法,所以會失敗。這里使用普通str的判斷方法即可
url = str(self.inputbox.toPlainText()) # 如果是Python2,這里需要str()轉(zhuǎn)換,如果是Python3則不用if url == ’’if len(url) == 0if url回答2:
url = str(self.inputbox.toPlainText())if url: #非空else: #空
相關(guān)文章:
1. 跟著課件一模一樣的操作使用tp6,出現(xiàn)了錯誤2. PHP類屬性聲明?3. node.js - 初次安裝vue-cli遇到的問題4. javascript - 安裝了babel,不起作用5. css - 這些字體是怎么弄的?6. angular.js - 這是什么錯?誰遇到過?給點提示7. android - 關(guān)于百度定位的問題8. transform - css3 translate 的水平垂直居中問題求解9. 前端 - 應(yīng)該先從angularJS , vue.js , react 這些框架中的哪個開始入手?10. css3 - css before 中文亂碼?
