c++ - Qt 对话框窗口禁用 alwaysontop 导致窗口关闭

标签 c++ qt dialog

我正在创建一个带有这些标志的对话窗口:

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

考虑到创建的对话窗口按要求保持在顶部,这很好用。但是,对话框窗口还有一个复选框,其目的是让用户禁用其 alwaysontop 属性,为此,这些代码行出现在类构造函数中:

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

函数是:

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

问题是,一旦取消选中复选框 alwaysontop,窗口就会消失(看起来它不再存在)。知道我做错了什么吗?

最佳答案

在窗口上调用 setWindowFlags()documented使窗口变为 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.

您只需调用show()使用 setWindowFlags() 后,这里是一个最小的例子:

#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();
}

看看 Window Flags Example ,并注意那里也调用了 show()

关于c++ - Qt 对话框窗口禁用 alwaysontop 导致窗口关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40819955/

相关文章:

带有对话框主题的Android底部按钮栏和 ScrollView

c++ - get_time 未按预期运行

android - 我需要在 Android Studio 中构建 NDK。但它返回错误

c++ - Qt 命名空间的元类型信息

c++ - htonl 出现段错误

c++ - Qt Creator,项目套件中的编译器被忽略

c++ - 将 C++ 模块连接到 QML - ReferenceError : <blank> is not defined

c++ - 使用 Qt、MFC 和 CMake 尝试/捕捉

android - Android 对话框中的 OnclickListener

c++ - QInputDialog 和 QMessageBox