正如我在标题中提到的,我想连接两个listiwdget。(或者可以使用组合框) 我想做的是,如果我单击第一个listwidget的项目,则第二个listwidget的项目将被更改。
尝试)我尝试如下连接两个listwidget
问题)当我单击第一个listwidget中的项目时,结果不是我想要的,并且无法在第二个listwidget中列出新项目。
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def __init__(self):
self.list1 = ["a","b","c","d"]
self.list2 = ["alpha","beta","gamma","delta","epsilon","zeta","eta","theta","lota","kappa"]
self.list3 = ["alpha","beta"]
self.list4 = ["gamma","delta"]
self.list5 = ["epsilon","zeta","eta","theta","lota","kappa"]
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(433, 509)
self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(70, 450, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.listWidget = QtWidgets.QListWidget(Dialog)
self.listWidget.setGeometry(QtCore.QRect(20, 10, 256, 192))
self.listWidget.setObjectName("listWidget")
self.listWidget.addItems(self.list1)
self.listWidget_2 = QtWidgets.QListWidget(Dialog)
self.listWidget_2.setGeometry(QtCore.QRect(20, 230, 256, 192))
self.listWidget_2.setObjectName("listWidget_2")
self.listWidget_2.addItems(self.list2)
self.retranslateUi(Dialog)
self.buttonBox.accepted.connect(Dialog.accept)
self.buttonBox.rejected.connect(Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
self.listWidget.itemActivated.connect(self.itemActivated_event)
def itemActivated_event(self, item):
print(item.text())
if print(item.text()) is "a":
self.listWidget_2.clear()
self.listWidget_2.addItems(self.list3)
elif print(item.text()) is "b":
self.listWidget_2.clear()
self.listWidget_2.addItems(self.list4)
else :
self.listWidget_2.clear()
self.listWidget_2.addItems(self.list5)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
我真正想要的是,
有很多问题,因为这是我第一次使用python和pyqt5。
答案 0 :(得分:0)
您有一个小错误:
而不是:
if (item.text()) is "a":
使用:
if (item.text()) == "a":
在Python中==和is运算符之间的差异
== operator
比较两个操作数的值并检查 为了价值平等。而is operator
检查是否 操作数是否引用相同的对象。