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下用的(當然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. 為什么我ping不通我的docker容器呢???2. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.3. 將SQLServer數(shù)據(jù)同步到MySQL 用什么方法?4. android - webview 自定義加載進度條5. 并發(fā)模型 - python將進程池放在裝飾器里為什么不生效也沒報錯6. numpy - python [:,2][:,None]是什么意思7. javascript - 微信小程序限制加載個數(shù)8. javascript - 微信小程序封裝定位問題(封裝異步并可能多次請求)9. javascript - 微信音樂分享10. python 怎樣用pickle保存類的實例?
