欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 文化 > QT 如何置顶窗口并激活

QT 如何置顶窗口并激活

2024/10/25 2:34:18 来源:https://blog.csdn.net/hellokandy/article/details/142755414  浏览:    关键词: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>//SetWindowPosMainWindow::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 activereturn;}else{
#if 1QThread::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}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com