尝试使用 QtableWidget 从中检索 QcomboBox 选择

Trying to retrieve QcomboBox selection from with QtableWidget

我有一个函数,它在 QtableWidget 的第一行插入多个 QcomboBox,然后更新从第 2 行开始的 excel 文件。这是我函数的结尾:

    for i in range(df.shape[1]):
        combo = comboCompanies(self)
        self.tableWidget.setCellWidget(0, i, combo)

我想做的是知道组合框上的其中一个索引何时更改,但它们目前具有相同的名称,因此我需要弄清楚如何唯一地标识它们。我找到了以下内容,但它不在 Python

        QComboBox* myComboBox = new QComboBox(); // making a new dropdown box
        myComboBox->setObjectName(QString::number(i)); // pass column number as object name
        connect(myComboBox, SIGNAL(currentIndexChanged(QString)), 
        SLOT(onComboChanged(QString)));
        ui->tableWidget->setCellWidget(0,i,myComboBox); // put box into table

如何在 Python 中编码?

您可以通过设置其对象名称或仅将其列作为参数传递给回调来识别您的组合框。

currentIndexChanged 信号只为您提供新的更改索引,而不是组合框本身。这就是我们必须使用内联 lambda 函数的原因。

这是使用了两个选项的代码:

import sys

from PyQt5.QtWidgets import QApplication, QTableWidget, QComboBox


def index_changed_id_by_column(column: int, selected_index: int) -> None:
    """combobox in column changed selected_index"""
    print(f"Combobox in column: {column}, changed to index:{selected_index}")


def index_changed_id_by_combobox(combobox: QComboBox, selected_index: int) -> None:
    """combobox changed selected_index"""
    print(f"Combobox: {combobox.objectName()}, changed to index:{selected_index}")


if __name__ == "__main__":
    app = QApplication(sys.argv)

    # Create some Table
    table = QTableWidget()
    table.setRowCount(2)
    table.setColumnCount(4)

    # Solution 1, using column index to identify Combobox
    for i in range(table.columnCount()):
        combobox = QComboBox()
        combobox.addItems(["Option 1", "Option 2", "Option 3"])
        '''
        This connects currentIndexChanged signal with lambda function (selected_index, column), 
        calling index_changed_id_by_column slot
        '''
        combobox.currentIndexChanged.connect(
            lambda selected_index, column=i: index_changed_id_by_column(column, selected_index))
        table.setCellWidget(0, i, combobox)

    # Solution 2, using objectName to identify Combobox
    for i in range(table.columnCount()):
        combobox = QComboBox()
        combobox.setObjectName(f"combobox_row1_coll{i}")
        combobox.addItems(["Option 1", "Option 2", "Option 3"])
        '''
        This connects currentIndexChanged signal with lambda function (selected_index, combobox), 
        calling index_changed_id_by_combobox slot
        '''
        combobox.currentIndexChanged.connect(
            lambda selected_index, combobox=combobox: index_changed_id_by_combobox(combobox, selected_index))
        table.setCellWidget(1, i, combobox)

    table.show()

    app.exec()

在第一行中,我们有调用 index_changed_id_by_column 回调的组合框。
在第二行 Comboboxes calling index_changed_id_by_combobox callback.

选择您的项目所需的那个。