Qt 中拖动无边框窗口遇到了问题,求大神帮忙
我做了一个窗口,把它设为了无边框,这样就无法实现拖动了。我网上看了好久,是要重写void mousePressEvent (QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
这三个函数,我重写了,但拖动窗口的时候程序就崩掉了,不知道为什么?
源码如下:
头文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMouseEvent>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
void mousePressEvent (QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
private:
Ui::MainWindow *ui;
bool shouldMove; //是否要改变窗口位置
QPoint *formerMainPos; //移动前窗口的位置
QPoint *formerMousePos; //第一次按下左键时鼠标的位置
};
#endif // MAINWINDOW_H
CPP文件:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setMouseTracking(true);
this->shouldMove=false;
this->setWindowFlags(Qt::FramelessWindowHint);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::mousePressEvent (QMouseEvent *event)
{
if (event->button()==Qt::LeftButton){
shouldMove = true;
*formerMainPos =this->pos();
*formerMousePos = event->globalPos();
event->accept();
}
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event){
if (event->button()==Qt::LeftButton){
shouldMove = false;
}
}
void MainWindow::mouseMoveEvent ( QMouseEvent * event )
{
QPoint point = event->globalPos();
if (shouldMove&&(event->button()==Qt::LeftButton))
{
int x = point.x()-formerMousePos->x();
int y = point.y()-formerMousePos->y();
this->move(formerMainPos->x()+x,formerMainPos->y()+y);
event->accept();
}
}
没多少分了,大神莫嫌弃。