使用组合框在qt对话框中切换不同的表

时间:2019-03-28 22:35:27

标签: c++ qt qt5 qtableview qcombobox

我想在一个对话框中显示一些表,可以通过qt对话框中的组合框进行切换。如何通过在组合框中选择相应的索引来切换到另一个表?我应该删除一个,然后添加一个新的...

dialog in qt

1 个答案:

答案 0 :(得分:2)

您可以使用QStackedWidget,一次只能查看一个窗口小部件,并根据currentIndex更改窗口小部件,如下例所示,另一种选择是使用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();
}