Skip to content

Instantly share code, notes, and snippets.

@peteristhegreat
Created January 13, 2017 21:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save peteristhegreat/d6564cd0992351f98aa94f869be36f77 to your computer and use it in GitHub Desktop.
Save peteristhegreat/d6564cd0992351f98aa94f869be36f77 to your computer and use it in GitHub Desktop.
QHoverEvent in a QPushButton (and leaveEvent and enterEvent)
#include <QApplication>
#include "mypushbutton.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyPushButton pb;
pb.show();
return a.exec();
}
#include "mypushbutton.h"
#include <QDebug>
MyPushButton::MyPushButton(QWidget *parent) :
QPushButton(parent)
{
setAttribute(Qt::WA_Hover);
// this->setMouseTracking(true);
m_count = 0;
this->setText(QString::number(m_count));
}
bool MyPushButton::event(QEvent * e)
{
switch(e->type())
{
case QEvent::HoverEnter:
hoverEnter(static_cast<QHoverEvent*>(e));
return true;
break;
case QEvent::HoverLeave:
hoverLeave(static_cast<QHoverEvent*>(e));
return true;
break;
case QEvent::HoverMove:
hoverMove(static_cast<QHoverEvent*>(e));
return true;
break;
default:
break;
}
return QWidget::event(e);
}
void MyPushButton::enterEvent(QEvent * e)
{
qDebug() << Q_FUNC_INFO << e->type();
}
void MyPushButton::leaveEvent(QEvent * e)
{
qDebug() << Q_FUNC_INFO << e->type();
}
void MyPushButton::hoverEnter(QHoverEvent * event)
{
qDebug() << Q_FUNC_INFO << event->type();
}
void MyPushButton::hoverLeave(QHoverEvent * event)
{
m_count = 0;
qDebug() << Q_FUNC_INFO << event->type();
this->setText(QString::number(m_count));
}
void MyPushButton::hoverMove(QHoverEvent * event)
{
m_count++;
qDebug() << Q_FUNC_INFO << event->type() << m_count;
this->setText(QString::number(m_count));
}
#ifndef MYPUSHBUTTON_H
#define MYPUSHBUTTON_H
#include <QPushButton>
#include <QHoverEvent>
#include <QEvent>
#include <QDebug>
class MyPushButton : public QPushButton
{
Q_OBJECT
public:
explicit MyPushButton(QWidget *parent = 0);
protected:
void enterEvent(QEvent *);
void leaveEvent(QEvent *);
bool event(QEvent * e);
void hoverEnter(QHoverEvent * event);
void hoverLeave(QHoverEvent * event);
void hoverMove(QHoverEvent * event);
signals:
public slots:
private:
int m_count;
};
#endif // MYPUSHBUTTON_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment