[Interest] Show window without 'active' or 'focus'

Nesuan Taiso nesuan23 at gmail.com
Tue Sep 29 11:15:01 CEST 2015


How do I show a window without making it 'active' or giving it 'focus'.

If I understand correctly:
- a widget may be 'active' in which case it is drawn differently, for 
example an 'active' QTextEdit has a blinking cursor.
- a widget may have 'focus' in which case it is the recipient of 
keyboard events.

These two flags are completely independent and it is possible for a 
widget to have any combination of these two flags, however many 
functions will set both together. Even parts of the documentation appear 
to blur the distinction between the two.

I want to show a hidden window without  either of these two flags, 
regardless of how the flags were set the last time the window was visible.

So far I have the following test case which toggles the visibility of a 
dialog every second.

[[[code]]]

#include <QtWidgets>

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

     QDialog dialog(0, Qt::WindowStaysOnTopHint);
     QTextEdit edit(&dialog);

     // This prevents Qt from activating the window
     // but does not help if the user activates the
     // window manually (by clicking it).
     dialog.setAttribute(Qt::WA_ShowWithoutActivating);

     auto timer = new QTimer;
     QObject::connect(timer, &QTimer::timeout,
         [&]() {
             dialog.setVisible(!dialog.isVisible());
         }
     );
     timer->start(1000);

     return a.exec();
}

[[[/code]]]

This code satisfies the no-focus requirement but fails the no-activate 
requirement because it never 'deactivates' the widget. This means that 
if the user ever activates the QTextEdit manually (by clicking it while 
it's visible) then the QTextEdit will remain 'active' for all subsequent 
setVisible(true).

How can I modify this code to satisfy both requirements?




More information about the Interest mailing list