2

所以基本上我刚开始学习 PyQt,我想在 listWidget 中获取元素的文本,但是每次我尝试 self.listWidget.currentItem().text() 都会引发错误。为什么?

import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QDialog, QApplication, QListWidget
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import *

class MainPage(QDialog):
    def __init__(self):
        super(MainPage,self).__init__()
        loadUi("HomePage.ui",self)
        self.pushButton.clicked.connect(self.addToList)
        self.selectButton.clicked.connect(self.getText)



    def addToList(self):
        customername = self.plainTextEdit_16.toPlainText()
        self.listWidget.addItem(customername)



    def getText(self):
        item = self.listWidget.currentItem().text() ##error is here

        print(item)


app = QApplication(sys.argv)

widget = MainPage()
widget.show()

sys.exit(app.exec_())
4

1 回答 1

3

假设“addToList”运行正确,那么唯一的错误是没有选择项目,因此 currentItem 将返回 None。解决方案是验证它是否为无:

def getText(self):
    item = self.listWidget.currentItem()
    if item is not None:
        print(it.text())
于 2020-02-16T09:39:29.607 回答