Glenn Ulysse Glenn Ulysse - 1 year ago 157
C++ Question

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);

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);
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?

Answer Source

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.");
    QObject::connect(&cb, &QCheckBox::toggled, &w, [&](){
            w.setWindowFlags(w.windowFlags() | Qt::WindowStaysOnTopHint);
            w.setWindowFlags(w.windowFlags() & ~Qt::WindowStaysOnTopHint);
        //call show() after changing window flags;

    return a.exec();

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download