Jiawei Lu
Jiawei Lu

Reputation: 577

Switch different tables in qt dialog using combobox

I would like to show some tables in one dialog, which can be switched by combobox in qt dialog. How can I switch to another table by select corresponding index in combobox? Should I delete one and add a new one...

dialog in qt

Upvotes: 1

Views: 308

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

You can use a QStackedWidget that allows you to view only one widget at a time and change the widget depending on the currentIndex as the following example, another option is to use QStackedLayout:

#include <QtWidgets>

static QTableWidget *create_table(const QString & name){
    QTableWidget *table = new QTableWidget(4, 4);
    for (int j = 0; j < table->columnCount(); ++j){
        table->setHorizontalHeaderItem(j, new QTableWidgetItem(QString("%1-%2").arg(name).arg(j)));
        for(int i=0; i< table->rowCount(); ++i){
            table->setItem(i, j, new QTableWidgetItem(QString::number(QRandomGenerator::global()->bounded(100))));
        }
    }
    return  table;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QStackedWidget *stacked = new QStackedWidget;
    QComboBox *combo = new QComboBox;

    QObject::connect(combo, QOverload<int>::of(&QComboBox::currentIndexChanged), stacked, &QStackedWidget::setCurrentIndex);

    for(const QString & name: {"A", "B", "C", "D", "E"}){
        QTableWidget *table = create_table(name);
        stacked->addWidget(table);
        combo->addItem(name);
    }

    QDialog w;
    QVBoxLayout *lay = new QVBoxLayout{&w};
    lay->addWidget(stacked);
    QHBoxLayout *hlay = new QHBoxLayout;
    hlay->addWidget(new QLabel("Layer"));
    hlay->addWidget(combo);
    lay->addLayout(hlay);
    w.show();
    return a.exec();
}

Upvotes: 2

Related Questions