QT中自定义了可移动按钮类(继承QPushButton),槽函数无用的问题

天真的 2019-07-11 05:48:22
本人萌新,QT也是刚学两天,我自定义了一个mybutton类,它继承自QPushButton类,添加了三个函数使之可在窗口内移动。之后想增加一个槽,使放开按钮时关闭窗口,却发现无法实现该功能。请问是什么原因,以及应该如何修改,求前辈指点。下面是我的代码。
mybutton.h
#ifndef MYBUTTON_H
#define MYBUTTON_H

#include <QWidget>
#include <QPushButton>
#include <QDebug>
#include <QPoint>

class mybutton : public QPushButton
{
Q_OBJECT
public:
mybutton(const QString & text, QWidget * parent = 0);

virtual void mouseMoveEvent(QMouseEvent * e);

virtual void mousePressEvent(QMouseEvent * e);

virtual void keyPressEvent(QKeyEvent * e);

private:
QPoint m_beginPos;
QPoint m_lastPos;

signals:

public slots:
};

#endif // MYBUTTON_H

mybutton.cpp
#include "mybutton.h"
#include "QMouseEvent"
#include "QKeyEvent"

mybutton::mybutton(const QString &text, QWidget *parent)
:QPushButton(text,parent)
{
}

void mybutton::mouseMoveEvent(QMouseEvent *e)
{
qDebug() << "mouse move!";

m_lastPos = e->pos();

int t_xDistance = m_lastPos.x() - m_beginPos.x();
int t_yDistance = m_lastPos.y() - m_beginPos.y();
if((this->x()+t_xDistance<=parentWidget()->width()-this->width()) && (this->y()+t_yDistance<=parentWidget()->height()-this->height()) && this->x()+t_xDistance>=0 && this->y()+t_yDistance>=0)
this->move(this->x()+t_xDistance,this->y()+t_yDistance);
}

void mybutton::mousePressEvent(QMouseEvent *e)
{
m_beginPos = e->pos();
}

void mybutton::keyPressEvent(QKeyEvent *e)
{
qDebug() << "key press!";

if(e->key() == Qt::Key_Left)
{
qDebug() << "key_left press!";
if(this->x()-4>=0)
this->move(this->x()-4,this->y());
}
else if(e->key() == Qt::Key_Right)
{
qDebug() << "key_right press!";
if(parentWidget()->width()-this->width()-this->x()-4>=0)
this->move(this->x()+4,this->y());
}
else if(e->key() == Qt::Key_Up)
{
qDebug() << "key_up press!";
if(this->y()-4>=0)
this->move(this->x(),this->y()-4);
}
else if(e->key() == Qt::Key_Down)
{
qDebug() << "key_down press!";
if(parentWidget()->height()-this->height()-this->y()-4>=0)
this->move(this->x(),this->y()+4);
}
}

widgetbutton.h
#ifndef WIDGETBUTTON_H
#define WIDGETBUTTON_H

#include <QWidget>
#include "mybutton.h"

class WidgetButton : public QWidget
{
Q_OBJECT

public:
WidgetButton(QWidget *parent = 0);
~WidgetButton();

private:
mybutton *m_moveBtn;
};

#endif // WIDGETBUTTON_H

widgetbutton.cpp
#include "widgetbutton.h"
#include "mybutton.h"

WidgetButton::WidgetButton(QWidget *parent)
: QWidget(parent)
{
m_moveBtn = new mybutton("move",this);
this->resize(400,400);
connect(m_moveBtn,SIGNAL(released()),this,SLOT(close()));//我想实现的功能
}

...全文
561 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
天真的 2019-07-12
  • 打赏
  • 举报
回复
可以解决,谢谢帮助。
huo5896324 2019-07-12
  • 打赏
  • 举报
回复
应该是你处理完这些鼠标事件后没有将事件再交给父类去处理,所以不会发送出released信号,你在每个事件里加上
QPushButton::xx事件(e);试试

16,216

社区成员

发帖
与我相关
我的任务
社区描述
Qt 是一个跨平台应用程序框架。通过使用 Qt,您可以一次性开发应用程序和用户界面,然后将其部署到多个桌面和嵌入式操作系统,而无需重复编写源代码。
社区管理员
  • Qt
  • 亭台六七座
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧