如何将函数与qlistWidget中的每个项相关联?

时间:2012-02-14 20:20:08

标签: python qt4 pyqt4

我的目标是当点击打开按钮时,它将显示目录中的所有文件。当您单击任何目录时,它将在另一个框架中显示该目录的内容。现在,我将如何将列表中的每个项目连接到一个将获取目录内容的函数。这是我的代码:

    from PyQt4 import QtCore, QtGui
import os

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(400, 300)
        self.buttonBox = QtGui.QDialogButtonBox(Dialog)
        self.buttonBox.setGeometry(QtCore.QRect(30, 240, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.frame = QtGui.QFrame(Dialog)
        self.frame.setGeometry(QtCore.QRect(20, 20, 361, 201))
        self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtGui.QFrame.Raised)
        self.frame.setObjectName("frame")
        self.listWidget = QtGui.QListWidget(self.frame)
        self.listWidget.setGeometry(QtCore.QRect(0, 0, 91, 201))
        self.listWidget.setObjectName("listWidget")
        self.widget = QtGui.QWidget(self.frame)
        self.widget.setGeometry(QtCore.QRect(110, 20, 120, 80))
        self.widget.setObjectName("widget")

        self.retranslateUi(Dialog)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), self.add)

    #QtCore.QObject.connect(self.listWidget, QtCore.SIGNAL("accepted()"), self.test)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def add(self):
    item=[]
    item = os.listdir('.')
    for value in item:
        self.listWidget.addItem(value)

    def test(self):
    print 'hello'   

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Dialog = QtGui.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

可能更简单的方法是使用这两个信号:

itemClicked(QListWidgetItem * item)

itemDoubleClicked(QListWidgetItem * item)
来自QListWidget的

例如:

QtCore.QObject.connect(self.listWidget, QtCore.SIGNAL("itemDoubleClicked(QListWidgetItem)"), self.test)

它应该调用self.test方法将当前的QListWidgetItem作为参数传递。