2
votes

Scenerio:
I have a 2 column QTreeWidget in my MainWindow. I add a row with text in the first column and a QComboBox in the second using the following code:

QTreeWidgetItem *rowItem = new QTreeWidgetItem(mainTree);
QComboBox *comboBox = GenerateComboBox(mainTree);
comboBox->setCurrentIndex(someIndexValue);
rowItem->setText(0,someText);
mainTree->setItemWidget(rowItem,1,comboBox);

My intention is to have a slot that does some work when the index of a combobox has changed. I need to know the row number of the TreeItem the changed comboBox resides in, in-addition to the index of the comboBox that value has changed to.


Current Understanding:
With my limited knowledge of QT:
1. It doesn't seem the TreeItem and comboBox are aware of each other as the TreeWidget is used as the parent for both.
2. I don't see a way to connect comboBox's indexChanged signal to a TreeItem itemChanged slot using what's already there to propagate the change notification up.


Question:
Is there a way to achieve this without writing a wrapper class that implements a slots and signal with the needed parameters or adding that implementation to the QTreeItem/QComboBox classes?

1

1 Answers

1
votes

You can use a lambda function:

#include <QtWidgets>

int main(int argc, char *argv[]) {
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);


    QTreeWidget * mainTree = new QTreeWidget;
    mainTree->setColumnCount(2);
    for (int i = 0; i < 10; ++i){
        QTreeWidgetItem *rowItem = new QTreeWidgetItem(mainTree);
        rowItem->setText(0, QString("item %1").arg(i));
        QComboBox * comboBox = new QComboBox();
        comboBox->addItems({"option1", "option2", "option3", "option4"});
        mainTree->setItemWidget(rowItem, 1, comboBox);

        QObject::connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), comboBox,
            [comboBox, rowItem](int index){
            qDebug() << index << comboBox << rowItem->text(0);
        });
    }

    QMainWindow w;
    w.setCentralWidget(mainTree);   
    w.resize(640, 480);
    w.show();

    return app.exec();
}