【问题标题】:How to connect comboboxes from a dynamic Table Widget?如何从动态表格小部件连接组合框?
【发布时间】:2023-03-09 09:15:02
【问题描述】:

我正在尝试创建一个表格小部件,其行数根据 SpinBox 变化。

我设法做到了。在表格小部件的每个单元格中,我有一个组合框。

我需要为表格小部件的每一行连接组合框。在接下来的两个组合框中自动选择“国家”时,会出现“首都”选项和对应的“城市”选项。

例如选择国家“美国”时:

  • 首都:华盛顿
  • 城市:芝加哥,纽约

我把代码写得更清楚。

from PyQt5 import QtCore, QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        central = QtWidgets.QWidget()
        self.setCentralWidget(central)
        layout = QtWidgets.QHBoxLayout(central)
        self.spin = QtWidgets.QSpinBox()
        layout.addWidget(self.spin)
        self.table = QtWidgets.QTableWidget(0, 3)
        layout.addWidget(self.table)
        self.table.verticalHeader().setVisible(False)
        for col, label in enumerate(('Country', 'Capital', 'City')):
            header = QtWidgets.QTableWidgetItem(label)
            self.table.setHorizontalHeaderItem(col, header)

        self.spin.setValue(self.table.rowCount())
        self.spin.valueChanged.connect(self.setRowCount)

    def setRowCount(self, count):
        if count == self.table.rowCount():
            return
        # if there are too many rows, remove them
        while self.table.rowCount() > count:
            self.table.removeRow(self.table.rowCount() - 1)
        # if rows are going to be added, create checkable items for them
        while self.table.rowCount() < count:
            row = self.table.rowCount()
            self.table.insertRow(row)

            dic = {"Country": ['Argentina', 'USA', 'Spain'], "Capital": ['Buenos Aires', 'Washington D.C.','Madrid'], "City1": ["Rosario", "Chicago", "Barcelona"],
                   "City2": ["Bariloche", "New York", "Osasuna"]}
            
            for i in range(self.table.columnCount()):
                if i==0:
                    combobox1 = QtWidgets.QComboBox()
                    combobox1.addItems(dic["Country"])
                    self.table.setCellWidget(row, i, combobox1)                    
                elif i==1:
                    combobox2 = QtWidgets.QComboBox()
                    combobox2.addItems(dic["Capital"])
                    self.table.setCellWidget(row, i, combobox2)
                elif i==2:
                    combobox3 = QtWidgets.QComboBox()
                    combobox3.addItems(dic["City1"])
                    combobox3.addItems(dic["City2"])
                    self.table.setCellWidget(row, i, combobox3)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    test = MainWindow()
    test.show()
    sys.exit(app.exec_())

【问题讨论】:

    标签: python python-3.x pyqt pyqt5 pyqt4


    【解决方案1】:

    如果您使用相同的索引保留字典和城市信息,那么使用您当前的代码非常容易。但我不确定这样做是否有效。

    无论如何,这是一个使用您当前代码的有效解决方案

    from functools import partial
    from PyQt5 import QtCore, QtWidgets
    
    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self):
            super().__init__()
            central = QtWidgets.QWidget()
            self.dic = {"Country": ['Argentina', 'USA', 'Spain'], "Capital": ['Buenos Aires', 'Washington D.C.','Madrid'], "City1": ["Rosario", "Chicago", "Barcelona"],
                       "City2": ["Bariloche", "New York", "Osasuna"]}
            self.setCentralWidget(central)
            layout = QtWidgets.QHBoxLayout(central)
            self.spin = QtWidgets.QSpinBox()
            layout.addWidget(self.spin)
            self.table = QtWidgets.QTableWidget(0, 3)
            layout.addWidget(self.table)
            self.table.verticalHeader().setVisible(False)
            for col, label in enumerate(('Country', 'Capital', 'City')):
                header = QtWidgets.QTableWidgetItem(label)
                self.table.setHorizontalHeaderItem(col, header)
    
            self.spin.setValue(self.table.rowCount())
            self.spin.valueChanged.connect(self.setRowCount)
    
        def setRowCount(self, count):
            if count == self.table.rowCount():
                return
            # if there are too many rows, remove them
            while self.table.rowCount() > count:
                self.table.removeRow(self.table.rowCount() - 1)
            # if rows are going to be added, create checkable items for them
            while self.table.rowCount() < count:
                row = self.table.rowCount()
                self.table.insertRow(row)
                
                for i in range(self.table.columnCount()):
                    if i==0:
                        combobox1 = QtWidgets.QComboBox()
                        combobox1.addItems(self.dic["Country"])
                        combobox1.currentIndexChanged.connect(partial(self.updateCity, row))
                        self.table.setCellWidget(row, i, combobox1)                    
                    elif i==1:
                        combobox2 = QtWidgets.QComboBox()
                        combobox2.addItems(self.dic["Capital"])
                        self.table.setCellWidget(row, i, combobox2)
                    elif i==2:
                        combobox3 = QtWidgets.QComboBox()
                        combobox3.addItems(self.dic["City1"])
                        self.table.setCellWidget(row, i, combobox3)
    
        def updateCity(self, index):
            current_index = self.sender().currentIndex()
            capital_widget = self.table.cellWidget(index, 1)
            city_widget = self.table.cellWidget(index, 2)
            capital_widget.setCurrentIndex(current_index)
            city_widget.setCurrentIndex(current_index)
    
    if __name__ == "__main__":
        import sys
        app = QtWidgets.QApplication(sys.argv)
        test = MainWindow()
        test.show()
        sys.exit(app.exec_())
    

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 2013-10-31
      相关资源
      最近更新 更多