当前位置:   article > 正文

QT自定义无边框窗口(可移动控制和窗口大小调整)_qt自定义标题栏无边框窗口

qt自定义标题栏无边框窗口

         QT是一个功能强大的跨平台开发框架,它提供了丰富的界面设计工具和组件。在界面开发中,QT窗口自带的标题栏无法满足我们的需求。我们就需要自定义无边框窗口,包括自定义标题栏和窗口大小调整功能。本文将介绍如何在QT中实现这些功能。

一、简述

         本文介绍了如何使用Qt框架创建一个无边框窗口,并提供了详细的源码,包括窗口样式设置、移动区域控制和窗口大小调整功能。用于设置窗口为无边框窗口。可为窗口添加自定义标题栏、边框和系统菜单按钮。

二、 设计思路             

        首先,在QT中,我们可以通过设置窗口属性为Qt::FramelessWindowHint来实现无边框窗口BaseWindow(由于系统窗口被设置为Qt::FramelessWindowHint会导致窗口不能被拖动,需要通过捕获鼠标移动事件从而实现窗口移动。)。

        然后,我们可以通过一个自定义的QWidget来扮演标题栏的角色BaseTitleBar。在这个自定义的QWidget中,我们可以添加一些控件,比如窗口标题,关闭按钮等。我们通过自定义的标题栏和边框样式来实现无边框窗口的外观。使用titleBar类来定义标题栏的样式,其中包括标题文本和关闭按钮。通过重写QWidget的mousePressEventmouseMoveEventmouseReleaseEvent函数,我们可以实现拖动窗口的功能。

        最后,自定义FramelessHelper一个辅助类,我们可以自定义窗口的行为,如设置窗口的可移动和可缩放属性。

三、效果 

四、核心代码  
1、头文件

BaseWindow.h 

  1. #ifndef BASEWINDOW_H
  2. #define BASEWINDOW_H
  3. #include <QWidget>
  4. #include <QMainWindow>
  5. #include "BaseTitleBar.h"
  6. class BaseWindow : public QWidget
  7. {
  8. Q_OBJECT
  9. public:
  10. BaseWindow(QWidget *parent = 0);
  11. ~BaseWindow();
  12. private:
  13. void initTitleBar();
  14. void paintEvent(QPaintEvent *event);
  15. void loadStyleSheet(const QString &sheetName);
  16. private slots:
  17. void onButtonMinClicked();
  18. void onButtonRestoreClicked();
  19. void onButtonMaxClicked();
  20. void onButtonCloseClicked();
  21. protected:
  22. BaseTitleBar* m_titleBar;
  23. };
  24. #endif // BASEWINDOW_H

 BaseTitleBar.h

  1. #ifndef BASETITLEBAR_H
  2. #define BASETITLEBAR_H
  3. #include <QWidget>
  4. #include <QLabel>
  5. #include <QPushButton>
  6. #include <QTimer>
  7. enum ButtonType
  8. {
  9. MIN_BUTTON = 0, // 最小化和关闭按钮;
  10. MIN_MAX_BUTTON , // 最小化、最大化和关闭按钮;
  11. ONLY_CLOSE_BUTTON // 只有关闭按钮;
  12. };
  13. class BaseTitleBar : public QWidget
  14. {
  15. Q_OBJECT
  16. public:
  17. BaseTitleBar(QWidget *parent = NULL);
  18. ~BaseTitleBar();
  19. // 设置标题栏背景色;
  20. void setBackgroundColor(int r, int g, int b);
  21. // 设置标题栏图标;
  22. void setTitleIcon(QString filePath);
  23. // 设置标题内容;
  24. void setTitleContent(QString titleContent);
  25. // 设置标题栏长度;
  26. void setTitleWidth(int width);
  27. // 设置标题栏上按钮类型;
  28. void setButtonType(ButtonType buttonType);
  29. // 设置标题栏中的标题是否会滚动;具体可以看效果;
  30. void setTitleRoll();
  31. // 保存/获取 最大化前窗口的位置及大小;
  32. void saveRestoreInfo(const QPoint point, const QSize size);
  33. void getRestoreInfo(QPoint& point, QSize& size);
  34. private:
  35. void paintEvent(QPaintEvent *event);
  36. void mouseDoubleClickEvent(QMouseEvent *event);
  37. void mousePressEvent(QMouseEvent *event);
  38. void mouseMoveEvent(QMouseEvent *event);
  39. void mouseReleaseEvent(QMouseEvent *event);
  40. // 初始化控件;
  41. void initControl();
  42. // 信号槽的绑定;
  43. void initConnections();
  44. // 加载样式文件;
  45. void loadStyleSheet(const QString &sheetName);
  46. signals:
  47. // 按钮触发的信号;
  48. void signalButtonMinClicked();
  49. void signalButtonRestoreClicked();
  50. void signalButtonMaxClicked();
  51. void signalButtonCloseClicked();
  52. private slots:
  53. // 按钮触发的槽;
  54. void onButtonMinClicked();
  55. void onButtonRestoreClicked();
  56. void onButtonMaxClicked();
  57. void onButtonCloseClicked();
  58. void onRollTitle();
  59. private:
  60. QLabel* m_pIcon; // 标题栏图标;
  61. QLabel* m_pTitleContent; // 标题栏内容;
  62. QPushButton* m_pButtonMin; // 最小化按钮;
  63. QPushButton* m_pButtonRestore; // 最大化还原按钮;
  64. QPushButton* m_pButtonMax; // 最大化按钮;
  65. QPushButton* m_pButtonClose; // 关闭按钮;
  66. // 标题栏背景色;
  67. int m_colorR;
  68. int m_colorG;
  69. int m_colorB;
  70. // 最大化,最小化变量;
  71. QPoint m_restorePos;
  72. QSize m_restoreSize;
  73. // 移动窗口的变量;
  74. bool m_isPressed;
  75. QPoint m_startMovePos;
  76. // 标题栏跑马灯效果时钟;
  77. QTimer m_titleRollTimer;
  78. // 标题栏内容;
  79. QString m_titleContent;
  80. // 按钮类型;
  81. ButtonType m_buttonType;
  82. };
  83. #endif // BASETITLEBAR_H

 framelesshelper.h

  1. #ifndef FRAMELESSHELPER_H
  2. #define FRAMELESSHELPER_H
  3. #include <QtGui>
  4. #include <QRubberBand>
  5. #include <QStylePainter>
  6. #include <QStyleOptionFocusRect>
  7. class WidgetData;
  8. /*****
  9. * FramelessHelperPrivate
  10. * 存储界面对应的数据集合,以及是否可移动、可缩放属性
  11. *****/
  12. class FramelessHelperPrivate
  13. {
  14. public:
  15. QHash<QWidget*, WidgetData*> m_widgetDataHash;
  16. bool m_bWidgetMovable : true;
  17. bool m_bWidgetResizable : true;
  18. bool m_bRubberBandOnResize : true;
  19. bool m_bRubberBandOnMove : true;
  20. };
  21. class FramelessHelper : public QObject
  22. {
  23. Q_OBJECT
  24. public:
  25. explicit FramelessHelper(QObject *parent = 0);
  26. ~FramelessHelper();
  27. // 激活窗体
  28. void activateOn(QWidget *topLevelWidget);
  29. // 移除窗体
  30. void removeFrom(QWidget *topLevelWidget);
  31. // 设置窗体移动
  32. void setWidgetMovable(bool movable);
  33. // 设置窗体缩放
  34. void setWidgetResizable(bool resizable);
  35. // 设置橡皮筋移动
  36. void setRubberBandOnMove(bool movable);
  37. // 设置橡皮筋缩放
  38. void setRubberBandOnResize(bool resizable);
  39. // 设置边框的宽度
  40. void setBorderWidth(uint width);
  41. // 设置标题栏高度
  42. void setTitleHeight(uint height);
  43. bool widgetResizable();
  44. bool widgetMovable();
  45. bool rubberBandOnMove();
  46. bool rubberBandOnResisze();
  47. uint borderWidth();
  48. uint titleHeight();
  49. protected:
  50. // 事件过滤,进行移动、缩放等
  51. virtual bool eventFilter(QObject *obj, QEvent *event);
  52. private:
  53. FramelessHelperPrivate *d;
  54. };
  55. class LinuxRubberBand : public QRubberBand
  56. {
  57. public:
  58. LinuxRubberBand(Shape s, QWidget * p = 0 )
  59. : QRubberBand( s, p )
  60. {
  61. QPalette palette;
  62. palette.setBrush( QPalette::WindowText, QBrush(Qt::lightGray) );
  63. setPalette(palette);
  64. repaint();
  65. }
  66. protected:
  67. virtual void paintEvent( QPaintEvent * )
  68. {
  69. QStylePainter painter(this);
  70. QStyleOptionFocusRect option;
  71. option.initFrom(this);
  72. QPen pen;
  73. pen.setStyle(Qt::DashLine);
  74. pen.setWidth(1);
  75. pen.setColor(QColor(Qt::red));
  76. painter.setPen(pen);
  77. painter.drawControl(QStyle::CE_FocusFrame, option);
  78. }
  79. };
  80. /*****
  81. * CursorPosCalculator
  82. * 计算鼠标是否位于左、上、右、下、左上角、左下角、右上角、右下角
  83. *****/
  84. class CursorPosCalculator
  85. {
  86. public:
  87. explicit CursorPosCalculator();
  88. void reset();
  89. void recalculate(const QPoint &globalMousePos, const QRect &frameRect);
  90. public:
  91. bool m_bOnEdges : true;
  92. bool m_bOnLeftEdge : true;
  93. bool m_bOnRightEdge : true;
  94. bool m_bOnTopEdge : true;
  95. bool m_bOnBottomEdge : true;
  96. bool m_bOnTopLeftEdge : true;
  97. bool m_bOnBottomLeftEdge : true;
  98. bool m_bOnTopRightEdge : true;
  99. bool m_bOnBottomRightEdge : true;
  100. static int m_nBorderWidth;
  101. static int m_nTitleHeight;
  102. };
  103. /*****
  104. * WidgetData
  105. * 更新鼠标样式、移动窗体、缩放窗体
  106. *****/
  107. class WidgetData
  108. {
  109. public:
  110. explicit WidgetData(FramelessHelperPrivate *d, QWidget *pTopLevelWidget);
  111. ~WidgetData();
  112. QWidget* widget();
  113. // 处理鼠标事件-划过、厉害、按下、释放、移动
  114. void handleWidgetEvent(QEvent *event);
  115. // 更新橡皮筋状态
  116. void updateRubberBandStatus();
  117. private:
  118. // 更新鼠标样式
  119. void updateCursorShape(const QPoint &gMousePos);
  120. // 重置窗体大小
  121. void resizeWidget(const QPoint &gMousePos);
  122. // 移动窗体
  123. void moveWidget(const QPoint &gMousePos);
  124. // 处理鼠标按下
  125. void handleMousePressEvent(QMouseEvent *event);
  126. // 处理鼠标释放
  127. void handleMouseReleaseEvent(QMouseEvent *event);
  128. // 处理鼠标移动
  129. void handleMouseMoveEvent(QMouseEvent *event);
  130. // 处理鼠标离开
  131. void handleLeaveEvent(QEvent *event);
  132. // 处理鼠标进入
  133. void handleHoverMoveEvent(QHoverEvent *event);
  134. private:
  135. FramelessHelperPrivate *d;
  136. LinuxRubberBand *m_pRubberBand;
  137. QWidget *m_pWidget;
  138. QPoint m_ptDragPos;
  139. CursorPosCalculator m_pressedMousePos;
  140. CursorPosCalculator m_moveMousePos;
  141. bool m_bLeftButtonPressed;
  142. bool m_bCursorShapeChanged;
  143. bool m_bLeftButtonTitlePressed;
  144. Qt::WindowFlags m_windowFlags;
  145. };
  146. #endif // FRAMELESSHELPER_H
2、实现代码

BaseWindow.cpp 

  1. #include "BaseWindow.h"
  2. #include <QDesktopWidget>
  3. #include <QApplication>
  4. #include <QPainter>
  5. #include <QFile>
  6. BaseWindow::BaseWindow(QWidget *parent)
  7. : QWidget(parent)
  8. {
  9. // FramelessWindowHint属性设置窗口去除边框;
  10. // WindowMinimizeButtonHint 属性设置在窗口最小化时,点击任务栏窗口可以显示出原窗口;
  11. this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinimizeButtonHint);
  12. // 设置窗口背景透明;
  13. setAttribute(Qt::WA_TranslucentBackground);
  14. // 初始化标题栏;
  15. initTitleBar();
  16. }
  17. BaseWindow::~BaseWindow()
  18. {
  19. }
  20. void BaseWindow::initTitleBar()
  21. {
  22. m_titleBar = new BaseTitleBar(this);
  23. m_titleBar->move(0, 0);
  24. connect(m_titleBar, SIGNAL(signalButtonMinClicked()), this, SLOT(onButtonMinClicked()));
  25. connect(m_titleBar, SIGNAL(signalButtonRestoreClicked()), this, SLOT(onButtonRestoreClicked()));
  26. connect(m_titleBar, SIGNAL(signalButtonMaxClicked()), this, SLOT(onButtonMaxClicked()));
  27. connect(m_titleBar, SIGNAL(signalButtonCloseClicked()), this, SLOT(onButtonCloseClicked()));
  28. }
  29. void BaseWindow::paintEvent(QPaintEvent* event)
  30. {
  31. //设置背景色;
  32. QPainter painter(this);
  33. QPainterPath pathBack;
  34. pathBack.setFillRule(Qt::WindingFill);
  35. pathBack.addRoundedRect(QRect(0, 0, this->width(), this->height()), 3, 3);
  36. painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
  37. painter.fillPath(pathBack, QBrush(QColor(127, 127, 127)));
  38. return QWidget::paintEvent(event);
  39. }
  40. void BaseWindow::loadStyleSheet(const QString &sheetName)
  41. {
  42. QFile file(":/Resources/" + sheetName + ".css");
  43. file.open(QFile::ReadOnly);
  44. if (file.isOpen())
  45. {
  46. QString styleSheet = this->styleSheet();
  47. styleSheet += QLatin1String(file.readAll());
  48. this->setStyleSheet(styleSheet);
  49. }
  50. }
  51. void BaseWindow::onButtonMinClicked()
  52. {
  53. if (Qt::Tool == (windowFlags() & Qt::Tool))
  54. {
  55. hide(); //设置了Qt::Tool 如果调用showMinimized()则窗口就销毁了???
  56. }
  57. else
  58. {
  59. showMinimized();
  60. }
  61. }
  62. void BaseWindow::onButtonRestoreClicked()
  63. {
  64. QPoint windowPos;
  65. QSize windowSize;
  66. m_titleBar->getRestoreInfo(windowPos, windowSize);
  67. this->setGeometry(QRect(windowPos, windowSize));
  68. }
  69. void BaseWindow::onButtonMaxClicked()
  70. {
  71. m_titleBar->saveRestoreInfo(this->pos(), QSize(this->width(), this->height()));
  72. QRect desktopRect = QApplication::desktop()->availableGeometry();
  73. QRect FactRect = QRect(desktopRect.x() - 3, desktopRect.y() - 3, desktopRect.width() + 6, desktopRect.height() + 6);
  74. setGeometry(FactRect);
  75. }
  76. void BaseWindow::onButtonCloseClicked()
  77. {
  78. close();
  79. }

BaseTitleBar.cpp

  1. #include "BaseTitleBar.h"
  2. #include <QHBoxLayout>
  3. #include <QPainter>
  4. #include <QFile>
  5. #include <QMouseEvent>
  6. #define BUTTON_HEIGHT 30 // 按钮高度;
  7. #define BUTTON_WIDTH 30 // 按钮宽度;
  8. #define TITLE_HEIGHT 30 // 标题栏高度;
  9. BaseTitleBar::BaseTitleBar(QWidget *parent)
  10. : QWidget(parent)
  11. , m_colorR(153)
  12. , m_colorG(153)
  13. , m_colorB(153)
  14. , m_isPressed(false)
  15. , m_buttonType(MIN_MAX_BUTTON)
  16. {
  17. // 初始化;
  18. initControl();
  19. initConnections();
  20. loadStyleSheet("MyTitle");
  21. }
  22. BaseTitleBar::~BaseTitleBar()
  23. {
  24. }
  25. // 初始化控件;
  26. void BaseTitleBar::initControl()
  27. {
  28. m_pIcon = new QLabel;
  29. m_pTitleContent = new QLabel;
  30. m_pButtonMin = new QPushButton;
  31. m_pButtonRestore = new QPushButton;
  32. m_pButtonMax = new QPushButton;
  33. m_pButtonClose = new QPushButton;
  34. m_pButtonMin->setFixedSize(QSize(BUTTON_WIDTH, BUTTON_HEIGHT));
  35. m_pButtonRestore->setFixedSize(QSize(BUTTON_WIDTH, BUTTON_HEIGHT));
  36. m_pButtonMax->setFixedSize(QSize(BUTTON_WIDTH, BUTTON_HEIGHT));
  37. m_pButtonClose->setFixedSize(QSize(BUTTON_WIDTH, BUTTON_HEIGHT));
  38. m_pTitleContent->setObjectName("TitleContent");
  39. m_pButtonMin->setObjectName("ButtonMin");
  40. m_pButtonRestore->setObjectName("ButtonRestore");
  41. m_pButtonMax->setObjectName("ButtonMax");
  42. m_pButtonClose->setObjectName("ButtonClose");
  43. QHBoxLayout* mylayout = new QHBoxLayout(this);
  44. mylayout->addWidget(m_pIcon);
  45. mylayout->addWidget(m_pTitleContent);
  46. mylayout->addWidget(m_pButtonMin);
  47. mylayout->addWidget(m_pButtonRestore);
  48. mylayout->addWidget(m_pButtonMax);
  49. mylayout->addWidget(m_pButtonClose);
  50. mylayout->setContentsMargins(5, 0, 0, 0);
  51. m_pTitleContent->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
  52. this->setFixedHeight(TITLE_HEIGHT);
  53. this->setWindowFlags(Qt::FramelessWindowHint);
  54. }
  55. // 信号槽的绑定;
  56. void BaseTitleBar::initConnections()
  57. {
  58. connect(m_pButtonMin, SIGNAL(clicked()), this, SLOT(onButtonMinClicked()));
  59. connect(m_pButtonRestore, SIGNAL(clicked()), this, SLOT(onButtonRestoreClicked()));
  60. connect(m_pButtonMax, SIGNAL(clicked()), this, SLOT(onButtonMaxClicked()));
  61. connect(m_pButtonClose, SIGNAL(clicked()), this, SLOT(onButtonCloseClicked()));
  62. }
  63. // 设置标题栏背景色,在paintEvent事件中进行绘制标题栏背景色;
  64. //在构造函数中给了默认值,可以外部设置颜色值改变标题栏背景色;
  65. void BaseTitleBar::setBackgroundColor(int r, int g, int b)
  66. {
  67. m_colorR = r;
  68. m_colorG = g;
  69. m_colorB = b;
  70. // 重新绘制(调用paintEvent事件);
  71. update();
  72. }
  73. // 设置标题栏图标;
  74. void BaseTitleBar::setTitleIcon(QString filePath)
  75. {
  76. QPixmap titleIcon(filePath);
  77. m_pIcon->setPixmap(titleIcon.scaled(25 , 25));
  78. }
  79. // 设置标题内容;
  80. void BaseTitleBar::setTitleContent(QString titleContent)
  81. {
  82. m_pTitleContent->setText(titleContent);
  83. m_titleContent = titleContent;
  84. }
  85. // 设置标题栏长度;
  86. void BaseTitleBar::setTitleWidth(int width)
  87. {
  88. this->setFixedWidth(width);
  89. }
  90. // 设置标题栏上按钮类型;
  91. // 由于不同窗口标题栏上的按钮都不一样,所以可以自定义标题栏中的按钮;
  92. // 这里提供了四个按钮,分别为最小化、还原、最大化、关闭按钮,如果需要其他按钮可自行添加设置;
  93. void BaseTitleBar::setButtonType(ButtonType buttonType)
  94. {
  95. m_buttonType = buttonType;
  96. switch (buttonType)
  97. {
  98. case MIN_BUTTON:
  99. {
  100. m_pButtonRestore->setVisible(false);
  101. m_pButtonMax->setVisible(false);
  102. }
  103. break;
  104. case MIN_MAX_BUTTON:
  105. {
  106. m_pButtonRestore->setVisible(false);
  107. }
  108. break;
  109. case ONLY_CLOSE_BUTTON:
  110. {
  111. m_pButtonMin->setVisible(false);
  112. m_pButtonRestore->setVisible(false);
  113. m_pButtonMax->setVisible(false);
  114. }
  115. break;
  116. default:
  117. break;
  118. }
  119. }
  120. // 设置标题栏中的标题是否会自动滚动,跑马灯的效果;
  121. // 一般情况下标题栏中的标题内容是不滚动的,但是既然自定义就看自己需要嘛,想怎么设计就怎么搞O(∩_∩)O!
  122. void BaseTitleBar::setTitleRoll()
  123. {
  124. connect(&m_titleRollTimer, SIGNAL(timeout()), this, SLOT(onRollTitle()));
  125. m_titleRollTimer.start(200);
  126. }
  127. // 保存窗口最大化前窗口的位置以及大小;
  128. void BaseTitleBar::saveRestoreInfo(const QPoint point, const QSize size)
  129. {
  130. m_restorePos = point;
  131. m_restoreSize = size;
  132. }
  133. // 获取窗口最大化前窗口的位置以及大小;
  134. void BaseTitleBar::getRestoreInfo(QPoint& point, QSize& size)
  135. {
  136. point = m_restorePos;
  137. size = m_restoreSize;
  138. }
  139. // 绘制标题栏背景色;
  140. void BaseTitleBar::paintEvent(QPaintEvent *event)
  141. {
  142. //设置背景色;
  143. QPainter painter(this);
  144. QPainterPath pathBack;
  145. pathBack.setFillRule(Qt::WindingFill);
  146. pathBack.addRoundedRect(QRect(0, 0, this->width(), this->height()), 3, 3);
  147. painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
  148. painter.fillPath(pathBack, QBrush(QColor(m_colorR, m_colorG, m_colorB)));
  149. // 当窗口最大化或者还原后,窗口长度变了,标题栏的长度应当一起改变;
  150. if (this->width() != this->parentWidget()->width())
  151. {
  152. this->setFixedWidth(this->parentWidget()->width());
  153. }
  154. QWidget::paintEvent(event);
  155. }
  156. // 双击响应事件,主要是实现双击标题栏进行最大化和最小化操作;
  157. void BaseTitleBar::mouseDoubleClickEvent(QMouseEvent *event)
  158. {
  159. // 只有存在最大化、还原按钮时双击才有效;
  160. if (m_buttonType == MIN_MAX_BUTTON)
  161. {
  162. // 通过最大化按钮的状态判断当前窗口是处于最大化还是原始大小状态;
  163. // 或者通过单独设置变量来表示当前窗口状态;
  164. if (m_pButtonMax->isVisible())
  165. {
  166. onButtonMaxClicked();
  167. }
  168. else
  169. {
  170. onButtonRestoreClicked();
  171. }
  172. }
  173. return QWidget::mouseDoubleClickEvent(event);
  174. }
  175. // 以下通过mousePressEvent、mouseMoveEvent、mouseReleaseEvent三个事件实现了鼠标拖动标题栏移动窗口的效果;
  176. void BaseTitleBar::mousePressEvent(QMouseEvent *event)
  177. {
  178. return QWidget::mousePressEvent(event);
  179. if (m_buttonType == MIN_MAX_BUTTON)
  180. {
  181. // 在窗口最大化时禁止拖动窗口;
  182. if (m_pButtonMax->isVisible())
  183. {
  184. m_isPressed = true;
  185. m_startMovePos = event->globalPos();
  186. }
  187. }
  188. else
  189. {
  190. m_isPressed = true;
  191. m_startMovePos = event->globalPos();
  192. }
  193. // return QWidget::mousePressEvent(event);
  194. }
  195. void BaseTitleBar::mouseMoveEvent(QMouseEvent *event)
  196. {
  197. if (m_isPressed)
  198. {
  199. QPoint movePoint = event->globalPos() - m_startMovePos;
  200. QPoint widgetPos = this->parentWidget()->pos();
  201. m_startMovePos = event->globalPos();
  202. this->parentWidget()->move(widgetPos.x() + movePoint.x(), widgetPos.y() + movePoint.y());
  203. }
  204. return QWidget::mouseMoveEvent(event);
  205. }
  206. void BaseTitleBar::mouseReleaseEvent(QMouseEvent *event)
  207. {
  208. m_isPressed = false;
  209. return QWidget::mouseReleaseEvent(event);
  210. }
  211. // 加载本地样式文件;
  212. // 可以将样式直接写在文件中,程序运行时直接加载进来;
  213. void BaseTitleBar::loadStyleSheet(const QString &sheetName)
  214. {
  215. QFile file(":/TitleBarRc/" + sheetName + ".css");
  216. file.open(QFile::ReadOnly);
  217. if (file.isOpen())
  218. {
  219. QString styleSheet = this->styleSheet();
  220. styleSheet += QLatin1String(file.readAll());
  221. this->setStyleSheet(styleSheet);
  222. }
  223. }
  224. // 以下为按钮操作响应的槽;
  225. void BaseTitleBar::onButtonMinClicked()
  226. {
  227. emit signalButtonMinClicked();
  228. }
  229. void BaseTitleBar::onButtonRestoreClicked()
  230. {
  231. m_pButtonRestore->setVisible(false);
  232. m_pButtonMax->setVisible(true);
  233. emit signalButtonRestoreClicked();
  234. }
  235. void BaseTitleBar::onButtonMaxClicked()
  236. {
  237. m_pButtonMax->setVisible(false);
  238. m_pButtonRestore->setVisible(true);
  239. emit signalButtonMaxClicked();
  240. }
  241. void BaseTitleBar::onButtonCloseClicked()
  242. {
  243. emit signalButtonCloseClicked();
  244. }
  245. // 该方法主要是让标题栏中的标题显示为滚动的效果;
  246. void BaseTitleBar::onRollTitle()
  247. {
  248. static int nPos = 0;
  249. QString titleContent = m_titleContent;
  250. // 当截取的位置比字符串长时,从头开始;
  251. if (nPos > titleContent.length())
  252. nPos = 0;
  253. m_pTitleContent->setText(titleContent.mid(nPos));
  254. nPos++;
  255. }

 framelesshelper.cpp

  1. #include "framelesshelper.h"
  2. int CursorPosCalculator::m_nBorderWidth = 5;
  3. int CursorPosCalculator::m_nTitleHeight = 30;
  4. /***** CursorPosCalculator *****/
  5. CursorPosCalculator::CursorPosCalculator()
  6. {
  7. reset();
  8. }
  9. void CursorPosCalculator::reset()
  10. {
  11. m_bOnEdges = false;
  12. m_bOnLeftEdge = false;
  13. m_bOnRightEdge = false;
  14. m_bOnTopEdge = false;
  15. m_bOnBottomEdge = false;
  16. m_bOnTopLeftEdge = false;
  17. m_bOnBottomLeftEdge = false;
  18. m_bOnTopRightEdge = false;
  19. m_bOnBottomRightEdge = false;
  20. }
  21. void CursorPosCalculator::recalculate(const QPoint &gMousePos, const QRect &frameRect)
  22. {
  23. int globalMouseX = gMousePos.x();
  24. int globalMouseY = gMousePos.y();
  25. int frameX = frameRect.x();
  26. int frameY = frameRect.y();
  27. int frameWidth = frameRect.width();
  28. int frameHeight = frameRect.height();
  29. m_bOnLeftEdge = (globalMouseX >= frameX &&
  30. globalMouseX <= frameX + m_nBorderWidth );
  31. m_bOnRightEdge = (globalMouseX >= frameX + frameWidth - m_nBorderWidth &&
  32. globalMouseX <= frameX + frameWidth);
  33. m_bOnTopEdge = (globalMouseY >= frameY &&
  34. globalMouseY <= frameY + m_nBorderWidth );
  35. m_bOnBottomEdge = (globalMouseY >= frameY + frameHeight - m_nBorderWidth &&
  36. globalMouseY <= frameY + frameHeight);
  37. m_bOnTopLeftEdge = m_bOnTopEdge && m_bOnLeftEdge;
  38. m_bOnBottomLeftEdge = m_bOnBottomEdge && m_bOnLeftEdge;
  39. m_bOnTopRightEdge = m_bOnTopEdge && m_bOnRightEdge;
  40. m_bOnBottomRightEdge = m_bOnBottomEdge && m_bOnRightEdge;
  41. m_bOnEdges = m_bOnLeftEdge || m_bOnRightEdge || m_bOnTopEdge || m_bOnBottomEdge;
  42. }
  43. /***** WidgetData *****/
  44. WidgetData::WidgetData(FramelessHelperPrivate *_d, QWidget *pTopLevelWidget)
  45. {
  46. d = _d;
  47. m_pWidget = pTopLevelWidget;
  48. m_bLeftButtonPressed = false;
  49. m_bCursorShapeChanged = false;
  50. m_bLeftButtonTitlePressed = false;
  51. m_pRubberBand = NULL;
  52. m_windowFlags = m_pWidget->windowFlags();
  53. m_pWidget->setMouseTracking(true);
  54. m_pWidget->setAttribute(Qt::WA_Hover, true);
  55. updateRubberBandStatus();
  56. }
  57. WidgetData::~WidgetData()
  58. {
  59. m_pWidget->setMouseTracking(false);
  60. m_pWidget->setWindowFlags(m_windowFlags);
  61. m_pWidget->setAttribute(Qt::WA_Hover, false);
  62. delete m_pRubberBand;
  63. m_pRubberBand = NULL;
  64. }
  65. QWidget* WidgetData::widget()
  66. {
  67. return m_pWidget;
  68. }
  69. void WidgetData::handleWidgetEvent(QEvent *event)
  70. {
  71. switch (event->type())
  72. {
  73. default:
  74. break;
  75. case QEvent::MouseButtonPress:
  76. handleMousePressEvent(static_cast<QMouseEvent*>(event));
  77. break;
  78. case QEvent::MouseButtonRelease:
  79. handleMouseReleaseEvent(static_cast<QMouseEvent*>(event));
  80. break;
  81. case QEvent::MouseMove:
  82. handleMouseMoveEvent(static_cast<QMouseEvent*>(event));
  83. break;
  84. case QEvent::Leave:
  85. handleLeaveEvent(static_cast<QMouseEvent*>(event));
  86. break;
  87. case QEvent::HoverMove:
  88. handleHoverMoveEvent(static_cast<QHoverEvent*>(event));
  89. break;
  90. }
  91. }
  92. void WidgetData::updateRubberBandStatus()
  93. {
  94. if (d->m_bRubberBandOnMove || d->m_bRubberBandOnResize)
  95. {
  96. if (NULL == m_pRubberBand) {
  97. m_pRubberBand = new LinuxRubberBand(QRubberBand::Rectangle);
  98. }
  99. }
  100. else
  101. {
  102. delete m_pRubberBand;
  103. m_pRubberBand = NULL;
  104. }
  105. }
  106. void WidgetData::updateCursorShape(const QPoint &gMousePos)
  107. {
  108. if (m_pWidget->isFullScreen() || m_pWidget->isMaximized())
  109. {
  110. if (m_bCursorShapeChanged)
  111. {
  112. m_pWidget->unsetCursor();
  113. }
  114. return;
  115. }
  116. m_moveMousePos.recalculate(gMousePos, m_pWidget->frameGeometry());
  117. if(m_moveMousePos.m_bOnTopLeftEdge || m_moveMousePos.m_bOnBottomRightEdge)
  118. {
  119. m_pWidget->setCursor( Qt::SizeFDiagCursor );
  120. m_bCursorShapeChanged = true;
  121. }
  122. else if(m_moveMousePos.m_bOnTopRightEdge || m_moveMousePos.m_bOnBottomLeftEdge)
  123. {
  124. m_pWidget->setCursor( Qt::SizeBDiagCursor );
  125. m_bCursorShapeChanged = true;
  126. }
  127. else if(m_moveMousePos.m_bOnLeftEdge || m_moveMousePos.m_bOnRightEdge)
  128. {
  129. m_pWidget->setCursor( Qt::SizeHorCursor );
  130. m_bCursorShapeChanged = true;
  131. }
  132. else if(m_moveMousePos.m_bOnTopEdge || m_moveMousePos.m_bOnBottomEdge)
  133. {
  134. m_pWidget->setCursor( Qt::SizeVerCursor );
  135. m_bCursorShapeChanged = true;
  136. }
  137. else
  138. {
  139. if (m_bCursorShapeChanged)
  140. {
  141. m_pWidget->unsetCursor();
  142. m_bCursorShapeChanged = false;
  143. }
  144. }
  145. }
  146. void WidgetData::resizeWidget(const QPoint &gMousePos)
  147. {
  148. QRect origRect;
  149. if (d->m_bRubberBandOnResize)
  150. origRect = m_pRubberBand->frameGeometry();
  151. else
  152. origRect = m_pWidget->frameGeometry();
  153. int left = origRect.left();
  154. int top = origRect.top();
  155. int right = origRect.right();
  156. int bottom = origRect.bottom();
  157. origRect.getCoords(&left, &top, &right, &bottom);
  158. //int minWidth = m_pWidget->minimumWidth();
  159. //int minHeight = m_pWidget->minimumHeight();
  160. int minWidth = 40;
  161. int minHeight = 40;
  162. if (m_pressedMousePos.m_bOnTopLeftEdge)
  163. {
  164. left = gMousePos.x();
  165. top = gMousePos.y();
  166. }
  167. else if (m_pressedMousePos.m_bOnBottomLeftEdge)
  168. {
  169. left = gMousePos.x();
  170. bottom = gMousePos.y();
  171. }
  172. else if (m_pressedMousePos.m_bOnTopRightEdge)
  173. {
  174. right = gMousePos.x();
  175. top = gMousePos.y();
  176. }
  177. else if (m_pressedMousePos.m_bOnBottomRightEdge)
  178. {
  179. right = gMousePos.x();
  180. bottom = gMousePos.y();
  181. }
  182. else if (m_pressedMousePos.m_bOnLeftEdge)
  183. {
  184. left = gMousePos.x();
  185. }
  186. else if (m_pressedMousePos.m_bOnRightEdge)
  187. {
  188. right = gMousePos.x();
  189. }
  190. else if (m_pressedMousePos.m_bOnTopEdge)
  191. {
  192. top = gMousePos.y();
  193. }
  194. else if (m_pressedMousePos.m_bOnBottomEdge)
  195. {
  196. bottom = gMousePos.y();
  197. }
  198. QRect newRect(QPoint(left, top), QPoint(right, bottom));
  199. if (newRect.isValid())
  200. {
  201. if (minWidth > newRect.width())
  202. {
  203. if (left != origRect.left())
  204. newRect.setLeft(origRect.left());
  205. else
  206. newRect.setRight(origRect.right());
  207. }
  208. if (minHeight > newRect.height())
  209. {
  210. if (top != origRect.top())
  211. newRect.setTop(origRect.top());
  212. else
  213. newRect.setBottom(origRect.bottom());
  214. }
  215. if (d->m_bRubberBandOnResize)
  216. {
  217. m_pRubberBand->setGeometry(newRect);
  218. }
  219. else
  220. {
  221. m_pWidget->setGeometry(newRect);
  222. }
  223. }
  224. }
  225. void WidgetData::moveWidget(const QPoint& gMousePos)
  226. {
  227. if (d->m_bRubberBandOnMove)
  228. {
  229. m_pRubberBand->move(gMousePos - m_ptDragPos);
  230. }
  231. else
  232. {
  233. m_pWidget->move(gMousePos - m_ptDragPos);
  234. }
  235. }
  236. void WidgetData::handleMousePressEvent(QMouseEvent *event)
  237. {
  238. if (event->button() == Qt::LeftButton)
  239. {
  240. m_bLeftButtonPressed = true;
  241. m_bLeftButtonTitlePressed = event->pos().y() < m_moveMousePos.m_nTitleHeight;
  242. QRect frameRect = m_pWidget->frameGeometry();
  243. QRect moveRect(frameRect.x(), frameRect.y(), frameRect.width(), 30);
  244. m_pressedMousePos.recalculate(event->globalPos(), frameRect);
  245. m_ptDragPos = event->globalPos() - frameRect.topLeft();
  246. if (m_pressedMousePos.m_bOnEdges)
  247. {
  248. if (d->m_bRubberBandOnResize)
  249. {
  250. m_pRubberBand->setGeometry(frameRect);
  251. m_pRubberBand->show();
  252. }
  253. }
  254. else if (d->m_bRubberBandOnMove)
  255. {
  256. if (moveRect.contains(event->globalPos())) {
  257. m_pRubberBand->setGeometry(frameRect);
  258. m_pRubberBand->show();
  259. }
  260. }
  261. }
  262. }
  263. void WidgetData::handleMouseReleaseEvent(QMouseEvent *event)
  264. {
  265. if (event->button() == Qt::LeftButton)
  266. {
  267. m_bLeftButtonPressed = false;
  268. m_bLeftButtonTitlePressed = false;
  269. m_pressedMousePos.reset();
  270. if (m_pRubberBand && m_pRubberBand->isVisible())
  271. {
  272. m_pRubberBand->hide();
  273. m_pWidget->setGeometry(m_pRubberBand->geometry());
  274. }
  275. }
  276. }
  277. void WidgetData::handleMouseMoveEvent(QMouseEvent *event)
  278. {
  279. if (m_bLeftButtonPressed)
  280. {
  281. if (d->m_bWidgetResizable && m_pressedMousePos.m_bOnEdges)
  282. {
  283. resizeWidget(event->globalPos());
  284. }
  285. else if (d->m_bWidgetMovable && m_bLeftButtonTitlePressed)
  286. {
  287. moveWidget(event->globalPos());
  288. }
  289. }
  290. else if (d->m_bWidgetResizable)
  291. {
  292. updateCursorShape(event->globalPos());
  293. }
  294. }
  295. void WidgetData::handleLeaveEvent(QEvent *event)
  296. {
  297. Q_UNUSED(event)
  298. if (!m_bLeftButtonPressed)
  299. {
  300. m_pWidget->unsetCursor();
  301. }
  302. }
  303. void WidgetData::handleHoverMoveEvent(QHoverEvent *event)
  304. {
  305. if (d->m_bWidgetResizable)
  306. {
  307. updateCursorShape(m_pWidget->mapToGlobal(event->pos()));
  308. }
  309. }
  310. /*****FramelessHelper*****/
  311. FramelessHelper::FramelessHelper(QObject *parent)
  312. : QObject(parent),
  313. d(new FramelessHelperPrivate())
  314. {
  315. d->m_bWidgetMovable = true;
  316. d->m_bWidgetResizable = true;
  317. d->m_bRubberBandOnResize = false;
  318. d->m_bRubberBandOnMove = false;
  319. }
  320. FramelessHelper::~FramelessHelper()
  321. {
  322. QList<QWidget*> keys = d->m_widgetDataHash.keys();
  323. int size = keys.size();
  324. for (int i = 0; i < size; ++i) {
  325. delete d->m_widgetDataHash.take(keys[i]);
  326. }
  327. delete d;
  328. }
  329. bool FramelessHelper::eventFilter(QObject *obj, QEvent *event)
  330. {
  331. switch (event->type())
  332. {
  333. case QEvent::MouseMove:
  334. case QEvent::HoverMove:
  335. case QEvent::MouseButtonPress:
  336. case QEvent::MouseButtonRelease:
  337. case QEvent::Leave:
  338. {
  339. WidgetData *data = d->m_widgetDataHash.value(static_cast<QWidget*>(obj));
  340. if (data)
  341. {
  342. data->handleWidgetEvent(event);
  343. return true;
  344. }
  345. }
  346. }
  347. return QObject::eventFilter(obj, event);
  348. }
  349. void FramelessHelper::activateOn(QWidget *topLevelWidget)
  350. {
  351. if (!d->m_widgetDataHash.contains(topLevelWidget))
  352. {
  353. WidgetData *data = new WidgetData(d, topLevelWidget);
  354. d->m_widgetDataHash.insert(topLevelWidget, data);
  355. topLevelWidget->installEventFilter(this);
  356. }
  357. }
  358. void FramelessHelper::removeFrom(QWidget *topLevelWidget)
  359. {
  360. WidgetData *data = d->m_widgetDataHash.take(topLevelWidget);
  361. if (data)
  362. {
  363. topLevelWidget->removeEventFilter(this);
  364. delete data;
  365. }
  366. }
  367. void FramelessHelper::setRubberBandOnMove(bool movable)
  368. {
  369. d->m_bRubberBandOnMove = movable;
  370. QList<WidgetData*> list = d->m_widgetDataHash.values();
  371. foreach (WidgetData *data, list)
  372. {
  373. data->updateRubberBandStatus();
  374. }
  375. }
  376. void FramelessHelper::setWidgetMovable(bool movable)
  377. {
  378. d->m_bWidgetMovable = movable;
  379. }
  380. void FramelessHelper::setWidgetResizable(bool resizable)
  381. {
  382. d->m_bWidgetResizable = resizable;
  383. }
  384. void FramelessHelper::setRubberBandOnResize(bool resizable)
  385. {
  386. d->m_bRubberBandOnResize = resizable;
  387. QList<WidgetData*> list = d->m_widgetDataHash.values();
  388. foreach (WidgetData *data, list)
  389. {
  390. data->updateRubberBandStatus();
  391. }
  392. }
  393. void FramelessHelper::setBorderWidth(uint width)
  394. {
  395. if (width > 0)
  396. {
  397. CursorPosCalculator::m_nBorderWidth = width;
  398. }
  399. }
  400. void FramelessHelper::setTitleHeight(uint height)
  401. {
  402. if (height > 0)
  403. {
  404. CursorPosCalculator::m_nTitleHeight = height;
  405. }
  406. }
  407. bool FramelessHelper::widgetMovable()
  408. {
  409. return d->m_bWidgetMovable;
  410. }
  411. bool FramelessHelper::widgetResizable()
  412. {
  413. return d->m_bWidgetResizable;
  414. }
  415. bool FramelessHelper::rubberBandOnMove()
  416. {
  417. return d->m_bRubberBandOnMove;
  418. }
  419. bool FramelessHelper::rubberBandOnResisze()
  420. {
  421. return d->m_bRubberBandOnResize;
  422. }
  423. uint FramelessHelper::borderWidth()
  424. {
  425. return CursorPosCalculator::m_nBorderWidth;
  426. }
  427. uint FramelessHelper::titleHeight()
  428. {
  429. return CursorPosCalculator::m_nTitleHeight;
  430. }

        通过以上代码,我们可以实现一个具有自定义标题栏、窗口大小调整和可移动、可缩放属性的无边框窗口。这段代码提供了一种简单而有效的方法来实现自定义外观和交互方式的无边框窗口。可以根据自己的需求进行修改和定制,以满足不同应用程序的需要。

五、使用示例

以下是一个简单的示例代码,演示了如何在Qt中使用此控件:

CustomMainWindow.h
  1. #ifndef CUSTOMMAINWINDOW_H
  2. #define CUSTOMMAINWINDOW_H
  3. #include <QWidget>
  4. #include "BaseWindow.h"
  5. #include "framelesshelper.h"
  6. namespace Ui {
  7. class CustomMainWindow;
  8. }
  9. class CustomMainWindow : public BaseWindow
  10. {
  11. Q_OBJECT
  12. public:
  13. explicit CustomMainWindow(QWidget *parent = 0);
  14. ~CustomMainWindow();
  15. private:
  16. void initTitleBar();
  17. void framelesshelperInit();
  18. Ui::CustomMainWindow *ui;
  19. };
  20. #endif // CUSTOMMAINWINDOW_H
CustomMainWindow.cpp
  1. #include "CustomMainWindow.h"
  2. #include "ui_CustomMainWindow.h"
  3. CustomMainWindow::CustomMainWindow(QWidget *parent) :
  4. BaseWindow(parent),
  5. ui(new Ui::CustomMainWindow)
  6. {
  7. initTitleBar();
  8. framelesshelperInit();
  9. ui->setupUi(this);
  10. }
  11. CustomMainWindow::~CustomMainWindow()
  12. {
  13. delete ui;
  14. }
  15. void CustomMainWindow::initTitleBar()
  16. {
  17. m_titleBar->setBackgroundColor(71,76,78);
  18. m_titleBar->setTitleIcon(":/TitleBarRc/icon.png");
  19. m_titleBar->setTitleContent(QStringLiteral("这是一个可以滚动的标题!"));
  20. m_titleBar->setTitleRoll();
  21. m_titleBar->setButtonType(MIN_MAX_BUTTON);
  22. m_titleBar->setTitleWidth(this->width());
  23. }
  24. void CustomMainWindow::framelesshelperInit()
  25. {
  26. //this指的是要处理的窗体
  27. FramelessHelper *pHelper = new FramelessHelper(this);
  28. pHelper->activateOn(this); //激活当前窗体
  29. pHelper->setWidgetMovable(true); //设置窗体可移动
  30. pHelper->setWidgetResizable(true); //设置窗体可缩放
  31. pHelper->setRubberBandOnMove(false); //设置橡皮筋效果-可移动
  32. pHelper->setRubberBandOnResize(true); //设置橡皮筋效果-可缩放
  33. }

        现在,我们可以编译和运行该项目。当窗口显示出来时,您将会看到一个自定义的无边框窗口,包含自定义的标题栏和窗口大小调整按钮。您可以尝试拖动标题栏或点击窗口大小调整按钮来调整窗口的大小和位置。需要注意的是,使用自定义标题栏时需留够空间,不要被窗口内控件遮挡。

        通过以上步骤,我们成功地实现了在QT中创建自定义无边框窗口的目标,包括自定义标题栏和窗口大小调整功能。这使得我们可以根据自己的需要创建独特和个性化的窗口界面。

        谢谢您的阅读,希望本文能为您带来一些帮助和启发。如果您有任何问题或意见,请随时与我联系。祝您度过美好的一天!

六、源代码下载

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/911546
推荐阅读
相关标签
  

闽ICP备14008679号