Qt鼠标事件,窗口移动
程序员文章站
2022-07-14 09:37:26
...
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
virtual void mouseDoubleClickEvent(QMouseEvent *event);
virtual void mouseMoveEvent(QMouseEvent *event);
virtual void mousePressEvent(QMouseEvent *event);
virtual void mouseReleaseEvent(QMouseEvent *event);
virtual void wheelEvent(QWheelEvent *event);
private:
Ui::MainWindow *ui;
QPoint m_offset; //记录鼠标左键按下时窗口和鼠标的位置偏差
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMouseEvent>
#include <QTextCharFormat>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::mouseDoubleClickEvent(QMouseEvent *event)
{
if(Qt::LeftButton == event->button())
{
if(this->isFullScreen())
{
// this->showNormal();
this->setWindowState(Qt::WindowNoState);
}
else
{
// this->showFullScreen();
this->setWindowState(Qt::WindowFullScreen);
}
}
else
{
QMainWindow::mouseDoubleClickEvent(event);
}
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
if(Qt::LeftButton & event->buttons())
{
QPoint point;
point = event->globalPos() - m_offset;
this->move(point);
}
else
{
QMainWindow::mouseMoveEvent(event);
}
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if(Qt::LeftButton == event->button())
{
m_offset = event->globalPos() - this->pos(); //记录鼠标和窗口的位置偏差
//将鼠标形状换成“手”
QCursor cursor;
cursor.setShape(Qt::ClosedHandCursor); //“握拳”
// cursor.setShape(Qt::OpenHandCursor); //"手掌"
QApplication::setOverrideCursor(cursor);
}
else
{
QMainWindow::mousePressEvent(event);
}
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
if(Qt::LeftButton == event->button())
{
QApplication::restoreOverrideCursor();
}
else
{
QMainWindow::mouseReleaseEvent(event);
}
}
void MainWindow::wheelEvent(QWheelEvent *event)
{
if(event->delta() > 0)
{
ui->textEdit->zoomIn(); //目前字体缩放仍有很多限制,并不是每种情况都有效
}
else
{
ui->textEdit->zoomOut();
}
}
上一篇: Qt5.9+tslib1.4移植
推荐阅读