Glenn Ulysse
Glenn Ulysse

Reputation: 69

Qt Dialog Window disabling alwaysontop leads to window closing

I am creating a dialog window with those flags :

this->setWindowFlags(this->windowFlags() ^ Qt::WindowContextHelpButtonHint);
this->setWindowFlags(this->windowFlags() | Qt::WindowStaysOnTopHint);
ui.setupUi(this);

Which works fine considering the dialog window created stays on top as requested. However, the dialog window also has a checkbox whose purpose is to let the user disable its alwaysontop property, to this end those lines of code are present in the class constructor:

QObject::connect(ui.cbAlwaysOnTop, &QCheckBox::clicked, this, &SearchWindow::IsSetOnTop);

and the function is :

void IsSetOnTop() {
    if (ui.cbAlwaysOnTop->checkState())
        this->setWindowFlags(this->windowFlags() | Qt::WindowStaysOnTopHint);
    else
        this->setWindowFlags(this->windowFlags() ^ Qt::WindowStaysOnTopHint);//^ Qt::WindowStaysOnTopHint
}

The problem is that as soon as the checkbox alwaysontop is unchecked, the window simply disapears (seeminly it no longer exists). Any idea what I am doing wrong?

Upvotes: 0

Views: 466

Answers (1)

Mike
Mike

Reputation: 8355

Calling setWindowFlags() on a window is documented to cause the window to hide:

This function calls setParent() when changing the flags for a window, causing the widget to be hidden. You must call show() to make the widget visible again.

You just need to call show() after using setWindowFlags(), Here is a minimal example:

#include <QtWidgets>

int main(int argc, char* argv[]){
    QApplication a(argc, argv);

    QWidget w;
    QVBoxLayout layout(&w);
    QCheckBox cb("always on top check box.");
    layout.addWidget(&cb);
    QObject::connect(&cb, &QCheckBox::toggled, &w, [&](){
        if(cb.isChecked())
            w.setWindowFlags(w.windowFlags() | Qt::WindowStaysOnTopHint);
        else
            w.setWindowFlags(w.windowFlags() & ~Qt::WindowStaysOnTopHint);
        //call show() after changing window flags
        w.show();
        //^^^^^^^
    });

    w.show();

    return a.exec();
}

Have a look at the Window Flags Example, and notice the show() call there too.

Upvotes: 1

Related Questions