我是pyqt的新手,我正在尝试创建一个可以被其他函数调用的选择器listwidgets,传入项目以供用户选择并从用户从函数中选择的值中获取值。
这就是我要做的事情:
class SelectorDialog(QtGui.QWidget):
def __init__(self, parent=None):
super(SelectorDialog, self).__init__(parent)
QtGui.QWidget.__init__(self)
self.setWindowFlags(QtCore.Qt.Dialog)
self.setupUi(self)
someItems = ['itemA', 'itemB', 'itemSomething']
for item in someItems:
list = QtGui.QListWidgetItem(item)
self.listWidget.addItem(list)
#self.show()
def setupUi(self, Form):
Form.setWindowTitle('To which item?')
self.verticalLayoutWidget = QtGui.QWidget(Form)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 500, 150))
self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget)
self.listWidget = QtGui.QListWidget(self.verticalLayoutWidget)
self.verticalLayout.addWidget(self.listWidget)
self.okButton = QtGui.QPushButton("OK")
self.cancelButton = QtGui.QPushButton("Cancel")
self.hbox = QtGui.QHBoxLayout(self.verticalLayoutWidget)
self.hbox.addStretch(1)
self.hbox.addWidget(self.okButton)
self.hbox.addWidget(self.cancelButton)
self.verticalLayout.addLayout(self.hbox)
QtCore.QMetaObject.connectSlotsByName(Form)
self.cancelButton.clicked.connect(lambda: self.close())
self.okButton.clicked.connect(lambda: self.pick(self))
def pick(self, Form):
for item in self.listWidget.selectedItems():
picked = str(item.text())
print picked
def whichItem():
selector = SelectorDialog(parent)
#find out picked item by SelecteorDialog, how ?
答案 0 :(得分:1)
首先,如果您的对象是对话框,则最好从QDialog
继承,而不是QWidget
。这允许使用QDialog的accept()
和reject()
方法。
警告,我现在无法测试下面的内容,但它基于我编写的代码。
所以在setupUi
我做了以下更改:
self.cancelButton.clicked.connect(self.reject) # Clicked cancel
self.okButton.clicked.connect(self.accept) #Clicked accept
然后,当您调用对话框时,您可以检查用户是否实际“接受”了对话框或取消了对话框:
def whichItem():
selector = SelectorDialog(parent)
if selector.exec_() == QtGui.QDialog.Accepted:
picks = selector.getPicks()
然后在类定义中进行以下更改:
Class SelectorDialog(QtGui.QDialog):
...
def getPicks(self):
picked = []
for item in self.listWidget.selectedItems():
picked.append(str(item.text()))
return picked