当前位置: 首页 > article >正文

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


http://www.kler.cn/news/357557.html

相关文章:

  • 4G、5G通信中,“网络侧“含义
  • 【Linux】命令行下的增删查改之“查看”
  • 基于SpringBoot的旅游网站的设计与实现
  • Scroll 生态首个 meme 项目 $Baggor,我们可以有哪些期待?
  • 集群与分布式
  • Lua变量
  • 学习eNSP对准备华为认证有哪些帮助?
  • TypeScript中 interface接口 type关键字 enum枚举类型
  • Spring Boot视频网站:安全与可扩展性设计
  • python车牌号OCR识别(centos版)
  • MySQL的安装(windows,Centos,ubuntu)
  • 《深度学习》OpenCV EigenFaces算法 人脸识别
  • 数据抓取时,使用动态IP要注意哪些?
  • 【LeetCode】每日一题 2024_10_20 最小差值 I(模拟/数学/贪心)
  • SQL Server-导入和导出excel数据-注意事项
  • 【数据结构】AVL树(C++实现)
  • OpenCV高级图形用户界面(21)暂停程序执行并等待用户按键输入函数waitKey()的使用
  • Unity Spine优化思路
  • 【Python数据库操作】使用SQLite和MySQL进行数据存储和查询!
  • [Linux#67][IP] 报头详解 | 网络划分 | CIDR无类别 | DHCP动态分配 | NAT转发 | 路由器