![](/img/trans.png)
[英]pyqt5 combobox selected item share with another window (signal/slot)
[英]Change ComboBox item when another ComboBox item is changed in pyqt5
我的 GUI 中有两个组合框。 我想根据第一个 combobox 的选定值更改第二个 combobox 中的值。
就像第一个 combobox 包含值 a,b,c。 选择a时,第二个 combobox 将具有值 1,2,3。 选择B时,第二个ZA8284521647549D6ECBBBBBB00383A3C28BDZ将具有4,5,6等。
我正在尝试将 if else 语句与 currentText() 方法一起使用,但它没有改变。
这是我的代码:
python 用户界面:
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(832, 625)
Dialog.setStyleSheet("background-color: rgb(85, 255, 255);")
self.comboBox = QtWidgets.QComboBox(Dialog)
self.comboBox.setGeometry(QtCore.QRect(140, 190, 481, 41))
self.comboBox.setStyleSheet("background-color: rgb(255, 255, 255);")
self.comboBox.setObjectName("comboBox")
self.comboBox_2 = QtWidgets.QComboBox(Dialog)
self.comboBox_2.setGeometry(QtCore.QRect(140, 290, 481, 41))
self.comboBox_2.setStyleSheet("background-color: rgb(255, 255, 255);")
self.comboBox_2.setObjectName("comboBox_2")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
主要的
class cbox(QtWidgets.QDialog, Ui_Dialog):
def __init__(self):
super(cbox,self).__init__()
self.setupUi(self)
list_1 = ['a', 'b', 'c']
self.comboBox.addItems(list_1)
list_2 = ['1','2','3']
list_3 = ['4','5', '6']
list_4 = ['7','8','9']
if str(self.comboBox.currentText()) == 'a':
self.comboBox_2.addItems(list_2)
if str(self.comboBox.currentText()) == 'b':
self.comboBox_2.addItems(list_3)
if str(self.comboBox.currentText()) == 'c':
self.comboBox_2.addItems(list_4)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
mwin = cbox()
mwin.show()
sys.exit(app.exec_())
我怎样才能正确地做到这一点?
您必须使用currentIndexChanged
信号,并连接到更新另一个组合内容的 function。
class cbox(QtWidgets.QDialog, Ui_Dialog):
def __init__(self):
super(cbox,self).__init__()
self.setupUi(self)
list_1 = ['a', 'b', 'c']
self.comboBox.addItems(list_1)
list_2 = ['1','2','3']
list_3 = ['4','5', '6']
list_4 = ['7','8','9']
self.comboBox_2.addItems(list_2)
self.sub_lists = list_2, list_3, list_4 self.comboBox.currentIndexChanged.connect(self.updateCombo)
def updateCombo(self, index):
# first of all, clear the current contents of the combo
self.comboBox_2.clear()
# then, add the new items, based on the new index
self.comboBox_2.addItems(self.sub_lists[index])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.