Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modeless Qt window on top of parent, but not on top of other applications

I wish to have a Qt dialog window that:

  1. always stays on top of its parent (the main application window),
  2. allows the user to interact with the parent window, and
  3. does not always stay on top of other applications.

I've been able to achieve 1 and 3 by making the dialog modal, and I can achieve 1 and 2 by using the Qt::WindowStaysOnTopHint window flag. But I cannot manage to make all three work - is it possible?

In case answers are OS-specific, I mainly work on a Mac, but I would prefer a solution that also applies to Windows and Linux. Thanks!

like image 618
rrwick Avatar asked Aug 26 '15 01:08

rrwick


1 Answers

You could try to use QGuiApplication::applicationStateChanged. This way you get notified if the user enters or leaves your application. Just dynamically add and remove the Qt::WindowStaysOnTopHint flag for your window. If you have multiple windows, you can use QGuiApplication::focusWindowChanged together with the first one.

Edit: To make the dialog non-modal, either set NULL as it's parent, or set the windowModality-Property to Qt::NonModal and show the dialog using show and not open or exec

Example code in a subclass of QDialog:

connect(QApplication::instance(), SIGNAL(applicationStateChanged(Qt::ApplicationState)), this, SLOT(changeAlwaysOnTop(Qt::ApplicationState)));

...

void MyDialog::changeAlwaysOnTop(Qt::ApplicationState state)
{
    if (state == Qt::ApplicationActive)
        setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
    else
        setWindowFlags(windowFlags() & ~Qt::WindowStaysOnTopHint);
    show();
}
like image 120
Felix Avatar answered Nov 13 '22 02:11

Felix