使用QCheckBox从不同的类更改QComboBox项

时间:2018-05-10 13:03:14

标签: pyqt qcombobox qcheckbox

我试图找出如何从另一个类更改QComboBox中的项目。我已经尝试了几种方法,包括尝试从其他类填充项目。在下面的示例中,我将具有QCheckBox的类Widget1嵌入到MainWindow中,并在检查时尝试更改列表项但它不起作用。它将打印连接,但没有别的。谁能解释我做错了什么?感谢。

import sys
from PyQt5.QtWidgets import QWidget, QComboBox, QHBoxLayout, QApplication, QVBoxLayout, QCheckBox

class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.widget1 = Widget1
        self.hbox = QHBoxLayout()
        self.Combo_Box = QComboBox()
        self.hbox.addWidget(self.Combo_Box)
        self.hbox.addWidget(self.widget1())
        self.setLayout(self.hbox)
        self.list = ['1','2','3','4','5','6']
        self.Combo_Box.addItems(self.list)

    def change_ComboBox(self):
        print("connected")
        self.Combo_Box.clear()
        self.list2 = ['7', '8', '9', '10', '11', '12']
        self.Combo_Box.addItems(self.list2)

class Widget1(QWidget):
    def __init__(self):
        super(Widget1, self).__init__()
        self.vbox = QVBoxLayout()
        self.check_Box = QCheckBox(self)
        self.vbox.addWidget(self.check_Box)
        self.check_Box.clicked.connect(self.send_change_ComboBox)

    def send_change_ComboBox(self):
        self.mainwindow = MainWindow()
        if self.check_Box.isChecked():
            self.mainwindow.change_ComboBox()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    wnd = MainWindow()
    wnd.show()
    app.exec_()

1 个答案:

答案 0 :(得分:0)

试一试:

import sys
from PyQt5.QtWidgets import QWidget, QComboBox, QHBoxLayout, QApplication, QVBoxLayout, QCheckBox

class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.widget1   = Widget1(self)            
        self.hbox      = QHBoxLayout()
        self.Combo_Box = QComboBox()
        self.hbox.addWidget(self.Combo_Box)
        self.hbox.addWidget(self.widget1)     
        self.setLayout(self.hbox)
        self.initUi()

    def initUi(self): 
        self.Combo_Box.clear()    
        self.list = ['1','2','3','4','5','6']
        self.Combo_Box.addItems(self.list)

    def change_ComboBox(self):
        print("connected")
        self.Combo_Box.clear()
        self.list2 = ['7', '8', '9', '10', '11', '12']
        self.Combo_Box.addItems(self.list2)

class Widget1(QWidget):
    def __init__(self, parent=None):
        super(Widget1, self).__init__(parent)
        self.parent = parent

        self.vbox      = QVBoxLayout()
        self.check_Box = QCheckBox(self)
        self.vbox.addWidget(self.check_Box)
        self.check_Box.clicked.connect(self.send_change_ComboBox)

    def send_change_ComboBox(self):
        if self.check_Box.isChecked():
            self.parent.change_ComboBox()
        else:
            self.parent.initUi()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    wnd = MainWindow()
    wnd.show()
    app.exec_()

enter image description here