QT自定义窗口(无边框,自由拖动)

来源:互联网 发布:现代单片机的发展趋势 编辑:程序博客网 时间:2024/04/28 11:30

做项目中为了美观,很少使用QT自带的标题栏,取消边框,自己实现边框。自定义窗口,主要通过鼠标事件实现。重写QT窗口事件,具体参考代码注释。

#ifndef CUSTOMWINDOW_H#define CUSTOMWINDOW_H#include <QtGui/QDialog>class CustomWindow : public QDialog{Q_OBJECTpublic:CustomWindow(QWidget *parent = 0);~CustomWindow();protected:virtual void mousePressEvent(QMouseEvent *event);virtual void mouseMoveEvent(QMouseEvent *event);virtual void mouseReleaseEvent(QMouseEvent *event);private:boolmMoveing;QPoint    mMovePosition;};#endif // CUSTOMWINDOW_H

#include "customwindow.h"#include <QtGui/QMouseEvent>#include <QtGui/QApplication>CustomWindow::CustomWindow(QWidget *parent){mMoveing=false;//Qt::FramelessWindowHint 无边框    //Qt::WindowStaysOnTopHint 窗口在最顶端,不会拖到任务栏下面setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinimizeButtonHint |Qt::WindowStaysOnTopHint);this->setStyleSheet("QDialog{border:2px solid green;}");}CustomWindow::~CustomWindow(){}//重写鼠标按下事件void CustomWindow::mousePressEvent(QMouseEvent *event){mMoveing = true;//记录下鼠标相对于窗口的位置//event->globalPos()鼠标按下时,鼠标相对于整个屏幕位置//pos() this->pos()鼠标按下时,窗口相对于整个屏幕位置mMovePosition = event->globalPos() - pos();return QDialog::mousePressEvent(event);}//重写鼠标移动事件void CustomWindow::mouseMoveEvent(QMouseEvent *event){//(event->buttons() && Qt::LeftButton)按下是左键//鼠标移动事件需要移动窗口,窗口移动到哪里呢?就是要获取鼠标移动中,窗口在整个屏幕的坐标,然后move到这个坐标,怎么获取坐标?//通过事件event->globalPos()知道鼠标坐标,鼠标坐标减去鼠标相对于窗口位置,就是窗口在整个屏幕的坐标if (mMoveing && (event->buttons() && Qt::LeftButton)&& (event->globalPos()-mMovePosition).manhattanLength() > QApplication::startDragDistance()) {  move(event->globalPos()-mMovePosition);mMovePosition = event->globalPos() - pos();}return QDialog::mouseMoveEvent(event);}void CustomWindow::mouseReleaseEvent(QMouseEvent *event){mMoveing = false;}


效果如下图:



qt版本:4.8.6,开发环境:vs2010 
安装插件 qt-opensource-windows-x86-vs2010-4.8.6.exe  qt-vs-addin-1.1.10.exe
源代码下载地址:http://download.csdn.net/download/hiwubihe/9553897

技术在于交流、沟通,转载请注明出处并保持作品的完整性。
作者:程序人生  
原文:http://blog.csdn.net/hiwubihe/article/details/51712754


0 0
原创粉丝点击