0
点赞
收藏
分享

微信扫一扫

Qt 窗口置顶


Qt 窗口置顶_Qt

文章目录

  • 一、前言
  • 二、示例代码
  • 三、补充说明
  • 四、窗口透明
  • 五、参考

一、前言

    我们使用QT进行界面开发时,可能会遇到需要将窗口置顶的情况。最常见的就是,需要制作一个悬浮工具栏,悬浮菜单,甚至是悬浮的画板。这就意味这我们需要将这个窗口置顶于“系统”以及我们自己“软件”的窗口之上。
    其实实现的方法很简单,就是在创建这个窗口类的时候,在构造函数中的加一个Qt::WindowFlags 枚举标识 Qt::WindowStaysOnTopHint

Qt::WindowStaysOnBottomHint 值为:0x04000000
Informs the window system that the window should stay on bottom of all other windows

二、示例代码

Win2::Win2(QWidget *parent)
    : QWidget{parent}
{
    this->setWindowFlags(Qt::Widget | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
    new QLabel("Win2 =================", this);
}

或者

Widget::Widget(QWidget *parent)
    : QWidget(parent,Qt::Widget | Qt::WindowStaysOnTopHint)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
}

三、补充说明

    如果以上实现不太兼容,可以考虑 Windows 的原生接口。

步骤1,在工程文件pro中添加库:

win{
    LIBS += -lUser32
}

步骤2,为了保证窗口始终置顶,这里我在窗口中开启一个定时器去执行以下函数
cpp 中添加如下代码:

#ifdef Q_OS_WIN
        SetWindowPos((HWND)this->winId(), HWND_TOPMOST, this->x(), this->y(), this->width(), this->height(), SWP_SHOWWINDOW);
        SetWindowLong((HWND)this->winId(), GWL_EXSTYLE, GetWindowLong((HWND)this->winId(), GWL_EXSTYLE) | WS_EX_NOACTIVATE);
#endif

h 中添加如下代码:

#ifdef Q_OS_WIN
#include "Windows.h"
#endif

四、窗口透明

setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);//去掉标题栏
setAttribute(Qt::WA_TranslucentBackground, true);//设置窗口背景透明

五、参考

QT实现窗口置顶、置顶状态切换、多窗口置顶优先关系

Qt 调用 Windows 接口实现窗口置顶

Qt 中设置窗体(QWidget)透明度的几种方法


举报

相关推荐

0 条评论