3

I have created two QPushButton on two different QMainWindow. I am assigning focus to them randomly at a specific interval.Here is the code.

int main(int argc, char **argv){ QApplication a(argc, argv); QMainWindow *win1= new QMainWindow(); win1->resize(567,578); win1->move(67,30); win1->show(); QMainWindow *win2= new QMainWindow(); win2->resize(567,578); win2->move(97,580); win2->show(); win1->show(); //win2->setModal(true); QPushButton *but1 = new QPushButton(win1); but1->resize(80,20); but1->move(100,100); but1->setText("1"); but1->show(); QPushButton *but2 = new QPushButton(win2); but2->resize(80,20); but2->move(100,300); but2->setText("2"); but2->show(); while(1){ if((rand()%2) == 1){ //win2->lower(); win1->raise(); win1->activateWindow(); win1->setWindowState(Qt::WindowActive); win1->setFocus(Qt::ActiveWindowFocusReason); but1->setFocus(Qt::ActiveWindowFocusReason); } else{ //win1->lower(); win2->raise(); win2->activateWindow(); win2->setFocus(Qt::ActiveWindowFocusReason); but2->setFocus(Qt::ActiveWindowFocusReason); } qApp->processEvents(0x00); sleep(2); } 

But the problem is the title bar of the first window is not changing color(usually putting a window back-n-forth through the visual stack changes the color of the title-bar), even when it has become the top window visually

1
  • 2
    You shouldn't use sleep in Qt. Create a slot and use QTimer to call this slot periodically. Commented Jul 28, 2013 at 9:28

1 Answer 1

1

You will obtain the desired behavious if you change your last loop to something similar:

 while (1) { // Exits if both windows are closed if (!win1->isVisible() && (!win2->isVisible())) { return 0; } // Eventually changes the focus, if the desired window is still visible if((rand() % 2) == 1) { if (win1->isVisible()) { QApplication::setActiveWindow(win1); } } else { if (win2->isVisible()) { QApplication::setActiveWindow(win2); } } QTime now; now.start(); do { qApp->processEvents(0x00); } while (now.elapsed() < 2000); } 

Anyway, if you put your program to sleep, it will not respond to user input during that interval, so be careful. The implementation is quite ugly, but it checks if the windows to be focused is still visible (i.e. the user has not closed it) and eventually exits if both have been closed. Of course I suppose that you were only interested in the setActiveWindow() thing, so I've not spent much time in writing something beautiful!

Sign up to request clarification or add additional context in comments.

3 Comments

no, its not working. the title bar doesnot change its color, as it supposed to do
It works perfectly here, what version of Qt are you using and on which platform? Did you try to push your specebar when focus changes to check if the correct button is responding?
And? Isn't it responding?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.