因为工作原因,需要做一个悬浮框,做的时候百度了很多资料,没有找到比较完整的资料,分享下自己的经验。先上效果图

然后上代码,代码不是完成的代码段,但核心代码都在
/*
可能需要的头文件:
#include "qlist.h"
#include "qmainwindow.h"
#include "qwidget.h"
#include "qapplication.h"
#include "qdesktopwidget.h"
*/
widget = new QWidget(main_window); //new一个widget类窗口,并指定父窗口
//设置窗口置顶显示 无工具栏 无边框,置顶时使用Qt::Dialog可以使窗口在当前软件置顶而不会全局置顶
//缺点:但窗口还是会被菜单弹出的对话框盖住
widget->setWindowFlags(Qt::Dialog | Qt::Tool | Qt::FramelessWindowHint);
//设置窗口透明度,控件及窗口都会变透明
widget->setWindowOpacity(0.8);
//下面两种方式控件透明度不会发生变化,但我在使用时有些小问题,可自行尝试
//palette.setColor(QPalette::Background,QColor(0,0,0,70));
//widget->setPalette(palette);
//widget->setAttribute(Qt::WA_TranslucentBackground, true);
//创建一个label
QLabel *label = new QLabel("渲染图例", widget);
label->setMinimumSize(100, 35); //设置最小大小
label->setAlignment(Qt::AlignVCenter | Qt::AlignHCenter); //设置文字垂直水平居中
QFont font("Microsoft YaHei", 14, 75); //设置字体 字体 大小 加粗(权重)
label->setFont(font);
label_list.push_back(label);
QVBoxLayout *v_layout = new QVBoxLayout; //垂直布局
vlayout.push_back(v_layout);
v_layout->addWidget(label);
for (int i = 0; i < color.length();i++)
{
QHBoxLayout *h_layout = new QHBoxLayout; //水平布局
QLabel *label1 = new QLabel("", widget);
label1->setMinimumSize(100, 35);
palette.setColor(QPalette::Background,color.at(i)); //设置label控件背景颜色
label1->setAutoFillBackground(true); //不加这局没有效果
label1->setPalette(palette); //注意:这里在show之前设置背景颜色可能会失败
label_list.push_back(label1);
QLabel *label2 = new QLabel(name.at(i),widget);
label2->setAlignment(Qt::AlignVCenter | Qt::AlignHCenter);
label_list.push_back(label2);
h_layout->addWidget(label1);
h_layout->addWidget(label2);
hlayout.push_back(h_layout);
v_layout->addLayout(h_layout);
}
widget->setLayout(v_layout); //给窗口添加布局
//获取父窗口大小
QRect screenRect = main_window->geometry(); //获得父类窗口得大小
int screenx = screenRect.width(); //父窗口得宽
int screeny = screenRect.height(); //父窗口得高
widget->show(); //要先show出来,才能获得窗口得准确大小,否则获取到得窗口大小不准确
int w = widget->geometry().width();
int h = widget->geometry().height();
widget->move(SHOW_WIDE_SCALE*screenx-w, SHOW_HIGH_SCALE*screeny-h);
/* 9月4日更新,在无意中发现,多次平凡调用时,在调用show之前设置背景颜色会出现失败而不能设置成功的情况
具体原因我也不知道,但改为在调用show之后在设置背景颜色就不会失败
int index = 0;
for (auto i = 1; i < g_labellist.length()-1;i=i+2)
{
QPalette palette;
palette.setColor(QPalette::Background,color[index]);
g_labellist.at(i)->setAutoFillBackground(true);
g_labellist.at(i)->setPalette(palette);
index++;
}
*/
&spm=1001.2101.3001.5002&articleId=100143327&d=1&t=3&u=4dcbcfbdc6b54ff19d05d47ce0f91274)
2705

被折叠的 条评论
为什么被折叠?



