你给的代码报错form2.cpp:126:13: Out-of-line definition of 'mousePressEvent' does not match any declaration in 'Form2'
时间: 2024-04-06 07:30:41 浏览: 143
Qt-DrawingTool:基于Qt的Diagram-Scene-Example的绘图工具
5星 · 资源好评率100%
这个错误提示是因为在 form2.cpp 文件中重新定义了 mousePressEvent 函数,但是其声明与 Form2 类中的声明不一致,因此编译器无法匹配。解决方案是在 Form2 类中声明该函数,并将其设为 virtual:
```
class Form2 : public QWidget
{
Q_OBJECT
public:
explicit Form2(QWidget *parent = nullptr);
virtual ~Form2();
protected:
virtual void mousePressEvent(QMouseEvent *event) override;
virtual void mouseMoveEvent(QMouseEvent *event) override;
private:
QPoint m_pressPos;
QPoint m_windowPos;
};
```
然后在 form2.cpp 文件中重新定义该函数:
```
void Form2::mousePressEvent(QMouseEvent *event)
{
m_pressPos = event->pos();
m_windowPos = this->pos();
}
void Form2::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton)
{
QPoint delta = event->pos() - m_pressPos;
this->move(m_windowPos + delta);
}
}
```
这样就可以实现拖动无边框窗口的功能了。
阅读全文