版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xuan_xuan_2/article/details/82317763
1、 实例需求
将窗体背景色透明,根据图片形状显示透明窗体。
2、 实例实现
<1> 制作透明文字图片
<2> 代码实现
1、先把我们制作图片添加到工程里的资源文件中:
2、在MainWindow.h中添加代码:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
//add by dx ---20180902
#include <QMouseEvent>
//end by dx
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
//add by dx ---20180902
protected:
void mousePressEvent(QMouseEvent *e);
void mouseMoveEvent(QMouseEvent *e);
void mouseReleaseEvent(QMouseEvent *e);
private:
QPoint last;
//end by dx
};
#endif // MAINWINDOW_H
3、在MainWindow.cpp文件中添加代码:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//add by dx ---20180902
//去掉标题栏
this->setWindowFlags(Qt::FramelessWindowHint);
//设置窗体大小
this->setMinimumSize(503,308);
//设置背景透明
this->setAttribute(Qt::WA_TranslucentBackground, true);
//窗体添加样式,样式为CSS 样式表 1、background-image:url 添加图片 2、background-repeat:no-repeat 不平铺
this->setStyleSheet("background-image:url(:/new/prefix1/touming);backgroundrepeat:no-repeat;");
//end by dx
}
MainWindow::~MainWindow()
{
delete ui;
}
//add by dx ---20180902
void MainWindow::mousePressEvent(QMouseEvent *e)
{
last = e->globalPos();
}
void MainWindow::mouseMoveEvent(QMouseEvent *e)
{
int dx = e->globalX() - last.x();
int dy = e->globalY() - last.y();
last = e->globalPos();
move(x()+dx, y()+dy);
}
void MainWindow::mouseReleaseEvent(QMouseEvent *e)
{
int dx = e->globalX() - last.x();
int dy = e->globalY() - last.y();
move(x()+dx, y()+dy);
}
//end by dx
4、去掉MainWindow.ui中的菜单项(此处不删除的化窗体上会出现菜单项框非常难看):
未删除前的:
删除后的:
3、 效果图
今天讲解到现在结束了,想进行视频学习的小伙伴,可以进入我的视频教程进行学习,课程地址:https://edu.csdn.net/course/detail/7275,课程资源下载地址:https://download.csdn.net/download/xuan_xuan_2/10641579,欢迎大家前来学习交流。