Show a QWidget after pressing a button

I want to change a QWidget in a QMainWindow dynamically. Therefore, the old widget (if it exists) will be deleted, a new one will be constructed and added to the main window. The widget (_visualization) is a QMainWindow itself that contains a menu bar and a widget that shows an OSG scene graph. If I don´t call show() on the new widget, I will only see the menu bar, but not the scene graph.

My goal is to call show() , when the user clicks on a button. The button is connected with the outer QMainWindow (MyQMainWindow).

Unfortunately, when I call show() on _visualization in the connected method, the scene graph will not be shown. In contrast to that, the scene graph will be shown, if I call it in the constructor method ( loadVisualization(...) ).

MyQMainWindow::MyQMainWindow(QWidget *parent ) :
    QMainWindow(parent) {
    ...
    loadVisualization(...);
    connect(_ui->nextButton, SIGNAL(clicked()), this, SLOT(showNext()));
    ...
}

void MyQMainWindow::loadVisualization(QString filePath) {
    if (_visualization) {
        _heightWidgetLayout->removeWidget(_visualization);
        delete _visualization;
    }

    _visualization= new HeightVisualization(0, filePath);
    _visualization->setParent(_mainWindowWidget);
    _heightWidgetLayout->addWidget(_visualization);

    //_visualization->show();     // will work here
} 

void MyQMainWindow::showNext() {
    _visualization->show();       // does not work here!
}

I know that QT will call setVisible(...) on the widget. This method first tests some states in QT ( testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden) ). If I call show() in showNext() , these tests lead to a return without any change.

Is it a problem with connectors and slots? Is there a possibility to show the widget, when the user clicked on a button?


What I have learned is that it is easy to use stackedWidget.

You can then programmatically change it with this

currentPageIndex = (currentPageIndex + 1) % 3;
ui->stackedWidget->setCurrentIndex(0);

The 3 can be the total pages you have in your stack widget. You can either use currentPageIndex, or you can just create some constants with the page ids like I have done with the 0.

链接地址: http://www.djcxy.com/p/39296.html

上一篇: 无法将继承的类的方法设置为点击信号的插槽

下一篇: 按下按钮后显示QWidget