很多人觉得系统自带的标题栏太丑了,想要自绘一个标题栏,去掉了系统自带的标题栏后,就需要自己实现窗口移动,下面的代码就是实现窗口移动。
widget.h
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QPoint> #include <QMouseEvent> //引用鼠标类头文件 class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); QPoint last; //鼠标按下 void mousePressEvent(QMouseEvent *e); //鼠标移动 void mouseMoveEvent(QMouseEvent *e); //鼠标释放 void mouseReleaseEvent(QMouseEvent *e); signals: public slots: }; #endif // WIDGET_H
widget.cpp
#include "Widget.h" #include <QApplication> #include <QLabel> #include <QTimer> #include <QMovie> #include <QImage> #include <QGraphicsBlurEffect> //模糊效果 #include <QGraphicsColorizeEffect> //着色效果 #include <QGraphicsDropShadowEffect> //阴影效果 #include <QGraphicsOpacityEffect> //透明效果 Widget::Widget(QWidget *parent) : QWidget(parent) { QLabel* label = new QLabel(this); #if 0 label->setGeometry(0,0,200,200); QMovie* mv = new QMovie("../a.PNG"); label->setMovie(mv); //3秒后图片消失 QTimer::singleShot( 3*1000, label, SLOT(close())); //图片移动 label->move(200,200); mv->start(); #endif QImage *img = new QImage; img->load("../a.PNG"); //QImage 加载图片 #if 0 //水平翻转 *img = img->mirrored(true,false); //垂直翻转 *img = img->mirrored(false,true); //旋转60度角 QMatrix matrix; *img = img->transformed(matrix.rotate(60)); // 重新设置图片大小 *img = img->scaled(1000,1000,Qt::IgnoreAspectRatio); #endif #if 0 QGraphicsBlurEffect *effect = new QGraphicsBlurEffect(this); effect->setBlurRadius(3); //模糊值,值越大越模糊 QGraphicsColorizeEffect *effect = new QGraphicsColorizeEffect(this); effect->setColor(QColor(0,200,0));//着色 QGraphicsOpacityEffect *effect = new QGraphicsOpacityEffect(this); //设定透明值 effect->setOpacity(0.5);//透明效果 /* OuterGlowBitmapEffect(外发光) DropShadowBitmapEffect(阴影) EmbossBitmapEffect(浮雕) BlurBitmapEffect(模糊) BevelBitmapEffect(斜角)。 */ #endif #if 1 QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect(this); //设定阴影 effect->setOffset(100,400); effect->setColor(QColor(20,20,20)); effect->setBlurRadius(500); #endif label->setGraphicsEffect(effect);//设置label效果 label->setPixmap(QPixmap::fromImage(*img));//把图片加载到label } //鼠标按下 void Widget::mousePressEvent(QMouseEvent *e) { if(e->pos().rx()>1000 || e->pos().ry()>500) return ; last = e->globalPos(); } //鼠标移动 void Widget::mouseMoveEvent(QMouseEvent *e) { if(e->pos().rx()>1000 || e->pos().ry()>500) return ; int dx = e->globalX() - last.x(); int dy = e->globalY() - last.y(); last = e->globalPos(); move(x()+dx,y()+dy); } //鼠标释放 void Widget::mouseReleaseEvent (QMouseEvent *e) { if(e->pos().rx()>1000 || e->pos().ry()>500) return ; int dx = e->globalX() - last.x(); int dy = e->globalY() - last.y(); move(x()+dx, y()+dy); } int main(int argc,char** argv) { QApplication app(argc,argv); Widget w; //去掉标题栏 w.setWindowFlags(Qt::FramelessWindowHint); //设置背景透明 //w.setAttribute(Qt::WA_TranslucentBackground, true); //固定大小 w.setGeometry(300,200,1000,500); w.show(); return app.exec(); }