Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set QWidget on top of current application but not other application

Tags:

qt

I have an application with several windows. Each window is a QWidget without parent.

I want those QWidget to be on top of the application, but not on top of other application. It's like the windows in Visual Studio, for instance, when they are free. They can't be hidden by the main window, but can be by an other application.

I tried with "setWindowFlags(Qt::WindowStaysOnTopHint);" , but it keeps the QWidget on top of all the applications.

like image 253
Nagawica Avatar asked Dec 17 '13 08:12

Nagawica


1 Answers

Use SetWindowModality instead of WindowStayOnTopHint, and both modal modes (Qt::WindowModal and Qt::ApplicationModal) permit other applications to be on top of your modal window.

LE: You can read more about the difference between ApplicationModal and WindowModal in the QDialog's documentation page, here

LE 2: The problem is that you don't set a parent, so to solve this set a parent for every child window (everything except your main window) and everything will work as you expected (the child windows will be on top of the parent, but won't be on top of any other application windows):

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

    QWidget w;
    QVBoxLayout* layout = new QVBoxLayout(&w);
    QPushButton* btn = new QPushButton("Show a non-modal window");
    layout->addWidget(btn);
    QWidget* mainWindow = &w;
    QObject::connect(btn, &QPushButton::clicked, [mainWindow]()
        {
            QWidget* dlg = new QWidget(mainWindow);
            QVBoxLayout* dlgLayout = new QVBoxLayout(dlg);
            dlg->setWindowFlags(Qt::Window);
            QLabel* lbl = new QLabel("Non-modal window...", dlg);
            dlgLayout->addWidget(lbl);

            dlg->show();
        });
    w.show();
    return a.exec();
}
like image 93
Zlatomir Avatar answered Nov 16 '22 02:11

Zlatomir