如何链接多个组合框表中的两个组合框?

Posted

技术标签:

【中文标题】如何链接多个组合框表中的两个组合框?【英文标题】:How to link two comboboxes in a table of multiple comboboxes? 【发布时间】:2019-11-06 19:52:57 【问题描述】:

我正在尝试将第 1 列中的组合框的值与第 3 列中的框链接。在第 1 列中的值更改时,下拉组合框中的值需要更改为新的集合。单击按钮后,将添加具有类似组合框功能的新行。问题是唯一响应第 1 列中组合框值更改的行是在最近添加的行中。如何在根据需要添加行的同时保留所有行中的链接?

我目前已将活动行设置为最新。如何在单击组合框时获取活动行以激活该行?我将所有组合框存储在一个字典中。

我的尝试:

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(60, 100, 551, 331))
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(3)
        self.tableWidget.setRowCount(0)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(2, item)
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(60, 450, 75, 23))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "Col 1"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "Col 2"))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(_translate("MainWindow", "Col 3"))
        self.pushButton.setText(_translate("MainWindow", "PushButton"))

class mainWindow(Ui_MainWindow, QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(mainWindow, self).__init__(parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.populate_table)

    # Combo box creator templates
    def comboBox_populator(self,values):
        combo = QtWidgets.QComboBox()
        for element in values:
            combo.addItem(element)
        return combo

    # Action to do on vehcile change
    def onComboChange(self):
        # selVehNames = self.selVehNames
        self.switchTo = self.comboBoxRows[self.counter][0].currentText()
        if self.switchTo == [] or self.switchTo == '':
            pass
        else:
            if self.switchTo == 'a':
                col1Data3 = ['x','y','z']
            elif self.switchTo == 'b':
                col1Data3 = ['4','5','6']
            elif self.switchTo == 'c':
                col1Data3 = ['21','22','23']
            else:
                pass
            # Update dict with comboboxes
            # col1Data1 = self.comboBoxRows[self.counter][0]
            # col1Data2 = self.comboBoxRows[self.counter][1]
            # self.AllComboBoxes = [col1Data1, col1Data2, col1Data3]

            colDataBox3 = self.comboBox_populator(col1Data3)
            print(col1Data3)
            # self.comboBoxRows.update(self.counter:self.AllComboBoxes)
            self.tableWidget.setCellWidget(self.counter,2,colDataBox3)

    # Populate the table
    def populate_table(self):
        self.AllComboBoxes = []
        self.comboBoxRows = 

        # Table row information
        rowCountcur = self.tableWidget.currentRow()
        self.tableWidget.insertRow(rowCountcur+1)
        self.counter = rowCountcur + 1

        # General Data
        col1Data1 = ['a','b','c']
        col1Data2 = ['e','f','g']
        col1Data3 = ['x','y','z']

        # Create combobox
        colDataBox1 = self.comboBox_populator(col1Data1)
        colDataBox2 = self.comboBox_populator(col1Data2)
        colDataBox3 = self.comboBox_populator(col1Data3)
        self.AllComboBoxes = [colDataBox1, colDataBox2, colDataBox3]
        self.comboBoxRows.update(self.counter:self.AllComboBoxes)

        # Populate columns
        self.tableWidget.setCellWidget(self.counter,0,self.comboBoxRows[self.counter][0])
        # Populate vehicle list and cell, col 2
        self.tableWidget.setCellWidget(self.counter,1,self.comboBoxRows[self.counter][1])
        # Populate mission order list and cell, col 3
        self.tableWidget.setCellWidget(self.counter,2,self.comboBoxRows[self.counter][2])

        self.comboBoxRows[self.counter][0].currentTextChanged.connect(self.onComboChange)

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

【问题讨论】:

【参考方案1】:

您的问题是 self.counter 永远不会改变,因为 currentRow 不指示行号,并且在您的情况下它始终为 -1,因此 self.counter 将始终为 0。

问题的关键是获取QComboBox所在的行,获取方法如下:

在与 currentIndexChanged 信号关联的槽中使用sender() 获取组合框。

使用mapTo()方法从QTableWidget的viewport()获取QComboBox左上角的位置。

使用indexAt()方法获取的QModelIndex获取行。

另一方面,您可以使用 itemData 来存储另一个组合框相对于初始组合框的选项。

from PyQt5 import QtCore, QtGui, QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.m_tablewidget = QtWidgets.QTableWidget(0, 3)
        self.m_tablewidget.setHorizontalHeaderLabels(
            ["Col 1", "Col 2", "Col 3"]
        )
        self.m_button = QtWidgets.QPushButton("Add Row", clicked=self.onClicked)

        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        lay = QtWidgets.QVBoxLayout(central_widget)
        lay.addWidget(self.m_tablewidget)
        lay.addWidget(self.m_button, alignment=QtCore.Qt.AlignLeft)

    @QtCore.pyqtSlot()
    def onClicked(self):
        d = 
            "a": ["x", "y", "z"],
            "b": ["4", "5", "6"],
            "c": ["21", "22", "23"],
        
        combobox1 = QtWidgets.QComboBox()
        for k, v in d.items():
            combobox1.addItem(k, v)
        combobox2 = QtWidgets.QComboBox()
        combobox2.addItems(combobox1.currentData())

        combobox3 = QtWidgets.QComboBox()
        combobox3.addItems(["e", "f", "g"])

        combobox1.currentIndexChanged.connect(self.onCurrentTextChanged)

        rc = self.m_tablewidget.rowCount()
        self.m_tablewidget.insertRow(rc)

        for i, combo in enumerate((combobox1, combobox2, combobox3)):
            self.m_tablewidget.setCellWidget(rc, i, combo)

    @QtCore.pyqtSlot()
    def onCurrentTextChanged(self):
        combobox1 = self.sender()
        if not isinstance(combobox1, QtWidgets.QComboBox):
            return
        p = combobox1.mapTo(self.m_tablewidget.viewport(), QtCore.QPoint())
        ix = self.m_tablewidget.indexAt(p)
        if not ix.isValid() or ix.column() != 0:
            return
        r = ix.row()
        data = combobox1.currentData()
        combobox3 = self.m_tablewidget.cellWidget(r, 2)
        if not isinstance(combobox3, QtWidgets.QComboBox):
            return
        combobox3.clear()
        combobox3.addItems(data)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = MainWindow()
    w.resize(640, 480)
    w.show()

    sys.exit(app.exec_())

【讨论】:

我羡慕你的编程技巧。谢谢您的帮助。我永远也想不通。如果您有任何参考资料可以帮助我学习这些技巧,请告诉我。

以上是关于如何链接多个组合框表中的两个组合框?的主要内容,如果未能解决你的问题,请参考以下文章

如何将 Visual Basic 6 组合框与 Microsoft Access 2007 表中的字段链接

Access 2007 组合框显示表中的错误结果

组合框更改事件正在触发工作表中的任何更改

将两个选项按钮与单个组合框链接,用于不同的行源[关闭]

如何从同一表单中的另一个组合框填充组合框?

如何使用组合框在记录 ms 访问中搜索多个字段?