3

我在两个不同的 QMainWindow 上创建了两个 QPushButton。我以特定的时间间隔随机分配焦点。这是代码。

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);
}

但问题是第一个窗口的标题栏没有改变颜色(通常通过视觉堆栈来回放置一个窗口会改变标题栏的颜色),即使它已经成为视觉上的顶部窗口

4

1 回答 1

1

如果您将最后一个循环更改为类似的内容,您将获得所需的行为:

    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);
}

无论如何,如果你让你的程序进入睡眠状态,它不会在这段时间内响应用户输入,所以要小心。该实现非常难看,但它会检查要聚焦的窗口是否仍然可见(即用户尚未关闭它),如果两者都已关闭,则最终退出。当然我想你只对setActiveWindow()感兴趣,所以我没有花太多时间写一些漂亮的东西!

于 2013-07-28T08:10:01.053 回答