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

转自:https://stackoverflow.com/questions/5702553/pyqt-qtgui-qlistwidget-currentitemqtgui-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.

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值