简体   繁体   中英

how do i get text from QListWidgetItem

so basically i just started to learn PyQt and I want to get element's text in listWidget, but everytime i try self.listWidget.currentItem().text() it throws an error. Why?

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_())

Assuming that "addToList" runs correctly then the only error is that there is no item selected so the currentItem will return None. The solution is to verify that it is None:

def getText(self):
    item = self.listWidget.currentItem()
    if item is not None:
        print(it.text())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM