QT 如何置顶窗口并激活
基本上,客户端软件都会有置顶某个窗口的需求。置顶窗口+激活窗口,两者不是同一个问题。有时候窗口置顶了,并不代表该窗口属于激活状态。本文将尝试把这两个问题一起解决了,请看下文:
一、置顶窗口
通过函数setWindowFlags设置属性:Qt::WindowStaysOnTopHint 即可。
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//
this->setWindowFlags(Qt::WindowStaysOnTopHint);//top show
}
MainWindow::~MainWindow()
{
delete ui;
}
二、激活窗口
2.1、设置定时器
在窗口初始化时设置定时器,定时执行激活窗口的代码。至于缺点也显而易见:定时重复激活窗口,即使不需要重新激活窗口也会重复激活,浪费计算资源。
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//
this->setWindowFlags(Qt::WindowStaysOnTopHint);
QTimer *t = new QTimer;
t->start(500);
QObject::connect(t, &QTimer::timeout, [this]() {
this->raise(); //提升该窗口到父窗口堆栈的顶部
this->show(); //显示窗口
this->activateWindow(); //激活窗口
});
}
MainWindow::~MainWindow()
{
delete ui;
}
2.2、事件重载-休眠唤醒激活方法(推荐)
重载窗体类的changeEvent函数,通过监听QEvent::ActivationChange,来判断窗口是否处于激活状态,如果不是则激活窗口。
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include <QThread>
#include <windows.h>//SetWindowPos
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//
this->setWindowFlags(Qt::WindowStaysOnTopHint);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::changeEvent(QEvent *event)
{
QWidget::changeEvent(event);
if (event->type() == QEvent::ActivationChange)
{
if (this->isActiveWindow())
{
// The window is already active
return;
}
else
{
#if 1
QThread::msleep(10);
this->raise(); //主窗体显示堆栈置顶
this->show(); //显示窗体
this->activateWindow(); //激活主窗体
#else//same with prev method.
setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
::SetWindowPos((HWND)winId(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
#endif
}
}
}