3

I am working on Qt app. There I have QMainWindow and QWidget which is displayed independently and out of the window.

I want to achieve that if I click on that QWidget, the window doesn't come to the front. I.e if it is behind another app, it should remain like that.

I have created test app:

main.cpp

int main(int argc, char *argv[])
{
   QApplication app(argc, argv);
   MainWindow w;
   w.show();
   Widget mywidget;
   return app.exec();
}

Widget.cpp
namespace
{
 Qt::WindowFlags defaultWindowFlags()
 {
  Qt::WindowFlags f = 0;

  f |= Qt::X11BypassWindowManagerHint;
  f |= Qt::FramelessWindowHint;
  f |= Qt::WindowStaysOnTopHint;
  f |= Qt::CustomizeWindowHint;
  f |= Qt::WindowDoesNotAcceptFocus;  
  f |= Qt::Window;
 return f;
 }
}

Widget::Widget(QWidget *parent) : QWidget(parent, defaultWindowFlags())
{
 setFixedSize(100,100);
 setStyleSheet("background-color:blue;");
 move(56,89);
 setVisible(true);
}
Jens
  • 6,173
  • 2
  • 24
  • 43
RuLoViC
  • 825
  • 7
  • 23
  • _I want to achieve that if I click on that QWidget, the window doesn't come to the front._ I know that certain X11 window managers do this out-of-the-box (or can be configured to do so). We struggled with similar things on Windows and finally gave up. Managing the stacking in Windows (with a pure Qt solution) seems a hard topic to me. To get progress in your question, it might be helpful to [edit] and mention your target platform. – Scheff's Cat Oct 04 '20 at 09:38
  • I just made an MCVE and tested on Windows. A transient `QDialog` (with main win. as parent) is always on top of the main win. and brings the main win. to front when clicked. A non-transient `QDialog` (with no parent) is an independent window. Clicking on it brings it on top without changing the current stacking level of main win. I saw that you constructed `Widget mywidget;` without parent window as well. So, you're probably not on Windows (where it should work). (`f |= Qt::X11BypassWindowManagerHint;` let me believe this even more.) I guess it may be related to your specific window manager... – Scheff's Cat Oct 04 '20 at 10:05
  • @Scheff Sorry, I forgot to mention. I am on MacOS platform – RuLoViC Oct 05 '20 at 06:22
  • I can't reproduce the MainWindow coming to the top when you click on the widget. Only closing the widget brings the MainWindow to the top. (Mac OS 10.15.7, Qt 5.15.0) – Jens Oct 11 '20 at 22:03
  • @Jens Can you share the code you're using. I have tried it using Qt 5.15.0 and MacOS Catalina 10.15.7 and when I click on widget QMainWindow comes to the front. I would like to compare your code to mine to see whats different – RuLoViC Oct 12 '20 at 09:17
  • The difference was the missing defaultWindowFlags() method. I tested each flag for effects and posted my finding in the answer below – Jens Oct 13 '20 at 07:57

1 Answers1

2

Leave out the line f |= Qt::WindowDoesNotAcceptFocus;, this makes Qt keep the focus at the main window.

Jens
  • 6,173
  • 2
  • 24
  • 43