文章目录
实现效果
创建项目
项目源码
开发环境
实现效果
创建项目
首先创建项目,选择QMainWindow或者QWidget都可以;
窗体中加入Layout,选择Vertical Layout或者Horizontal Layout都可以,然后添加Widget控件在其中;
在MainWindow.h中加入eventFilter事件:
protected:
bool eventFilter(QObject *watched, QEvent *evt);
实现eventFilter事件:
bool MainWindow::eventFilter(QObject *watched, QEvent *evt)
{
static int index = 1;
static QPoint mousePoint;
static bool mousePressed = false;
QMouseEvent *event = static_cast<QMouseEvent *>(evt);
if (event->type() == QEvent::MouseButtonPress) {
if (event->button() == Qt::LeftButton) {//左键按下
mousePressed = true;
mousePoint = event->globalPos() - this->pos();
if (index == 4) {//循环图片索引
index = 1;
} else {
index++;
}
ui->widget->setStyleSheet(QString("background-image: url(:/%1.png);").arg(index));
return true;
} else {//鼠标右键退出
exit(0);
}
} else if (event->type() == QEvent::MouseButtonRelease) {//释放鼠标
mousePressed = false;
return true;
} else if (event->type() == QEvent::MouseMove) {//鼠标移动
if (mousePressed && (event->buttons() && Qt::LeftButton)) {
this->move(event->globalPos() - mousePoint);//窗体移动
return true;
}
}
return QWidget::eventFilter(watched, event);//事件传递
}
设置窗口属性:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setAttribute(Qt::WA_TranslucentBackground);//设置窗口透明显示
this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint);
ui->widget->installEventFilter(this);//启动事件
ui->widget->setStyleSheet(QString("background-image: url(:/%1.png);").arg(1));//设置背景图片
}
OK,大功告成,简单实用;
项目源码
GitHub:lizhifun / QtBGDemo
开发环境
Author:Lizhifun
OS:Windows 10 家庭中文版
Compiler:Microsoft Visual C++ Compiler 15.9.28307.1259(amd64)
Kit:Desktop Qt 5.14.2 MSVC2017 64bit
Qt Creator:4.11.1
参考文章:http://www.qtcn.org/bbs/read-htm-tid-63579.html