首页 > 技术知识 > 正文

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

.

#include <QtGui> #include <QtWidgets> #include <QMenuBar> #include <QMainWindow> #include “header/CustomWindow.h” CustomWindow::CustomWindow(QWidget *parent) { mMoveing = false; //Qt::FramelessWindowHint 无边框 //Qt::WindowStaysOnTopHint 窗口在最顶端,不会拖到任务栏下面 setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowStaysOnTopHint); } 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; }
<

.

实例

接下来是使用这个CustomWindow类的方法与实例:

// 在“图像处理自编系统”中,“预览”窗口及“关于”弹窗都用到了自定义窗口 // 为方便演示,在工具栏上加一按钮,以“关于”为例。 QPushButton *button = new QPushButton(tr(“关于”)); ui.mainToolBar->addWidget(button); connect(button, SIGNAL(clicked()), this, SLOT(showWin())); // 下面完善槽函数 void mainWindow::showWin() { CustomWindow *helpWin = new CustomWindow(); // 此处对类进行实例化 helpWin->resize(600, 400); // 设置图像大小 QLabel *label_about = new QLabel(helpWin); label_about->setText(tr(“图像处理自编软件 1.0 版”)); QLabel *label_right = new QLabel(helpWin); label_right->setText(tr(“Copyright (C) 2018 深圳 ATR”)); QLabel *label_author = new QLabel(helpWin); label_author->setText(tr(“作者:笔尖 http://blog.csdn.net/u013165921”)); QPushButton *button_ok = new QPushButton(helpWin); button_ok->setText(tr(“确定”)); connect(button_ok, SIGNAL(clicked()), helpWin, SLOT(close())); label_about->move(100, 100); label_right->move(100, 180); label_author->move(100, 260); button_ok->move(400, 180); helpWin->exec(); // 模态对话框,关闭该子窗口前不能对主窗口进行任何操作。 }
<

原文连接:https://blog.csdn.net/u013165921/article/details/79391330

猜你喜欢