Search code examples
pyqtqlistwidget

pyqt QtGui.QListWidget.currentItem(QtGui.QListWidget()) is always None


I have QListWidget in my app, I need to get string value of item from QListWidget on which user has double clicked (activated item).

QtCore.QObject.connect(self.ui.listWidget, QtCore.SIGNAL("itemActivated (QListWidgetItem *)"), self.cas_dialog_spust)

def cas_dialog_spust(self):
    predmet = QtGui.QListWidget.currentItem(QtGui.QListWidget())
    print(predmet)
    strpredmet = QtGui.QListWidgetItem.text(QtGui.QListWidgetItem(predmet))
    print(strpredmet) 

When I actually run this I double click on Item in QListWidget, predmet is None and I really don't know why.


Solution

  • You don't seem to understand the API calls you need to get the text of a QListWidgetItem. currentItem() returns a QListWidgetItem, and text() returns a string; both don't take any arguments. Here's a little application that does exactly what you request; let me know if you need any clarification.

    import sys
    from PyQt4.QtGui import QApplication, QWidget, QListWidget, QHBoxLayout
    
    class ListWindow(QWidget):
        def __init__(self, parent=None):
            super(ListWindow, self).__init__(parent)
            self.listWidget = QListWidget()
            for i in range(1, 11):
                self.listWidget.addItem("Item {}".format(i))
            self.listWidget.itemActivated.connect(self.printItemText)
            mainLayout = QHBoxLayout()
            mainLayout.addWidget(self.listWidget)
            self.setLayout(mainLayout)
    
        def printItemText(self, item):
            """These two are equivalent"""
            print(item.text())
            print(self.listWidget.currentItem().text())
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        listWindow = ListWindow()
        listWindow.show()
        app.exec_()