How to emit a signal from a QPushButton when the m

2019-01-19 05:40发布

Recently, I wanted that QPushButton can emit a signal, when the mouse pointer enters. How can I make it?

I know that QPushButton has some already defined signal, such as clicked(), pressed(), destory() and so on. But no signal like hover(), enter(), ...

I looked some information about it: Someone said it can be done by css. I don't understand. Can you give me some advice ? Thank you!

标签: qt mousehover
4条回答
手持菜刀,她持情操
2楼-- · 2019-01-19 06:11

Make sure to add ':' after the public keyword

public: Q_SIGNALS:
    void hovered();
查看更多
混吃等死
3楼-- · 2019-01-19 06:12

Although @Exa has answered this question, I want to show another solution which does not need to subclass QPushButton and is flexible in use! ( That's what I need in my project)

Step 1/2 : Overriding eventFilter.

LoginWindow.h:

// LoginWindow is where you placed your QPushButton 
//(= most probably your application windows)

class LoginWindow: public QWidget
{
public:
      bool eventFilter(QObject *obj, QEvent *event);
..
};

LoginWindow.cpp:

bool LoginWindow::eventFilter(QObject *obj, QEvent *event)
{
    // This function repeatedly call for those QObjects
    // which have installed eventFilter (Step 2)

    if (obj == (QObject*)targetPushButton) {
        if (event->type() == QEvent::Enter)
        {
        // Whatever you want to do when mouse goes over targetPushButton
        }
        return true;
    }else {
        // pass the event on to the parent class
        return QWidget::eventFilter(obj, event);
    }
}

Step 2/2 : Installing eventFilter on target widgets.

LoginWindow::LoginWindow()
{
    ...
    targetPushButton->installEventFilter(this);
    ...
}
查看更多
地球回转人心会变
4楼-- · 2019-01-19 06:17

If I remember correctly, you need to enable mouse tracking for the button (Qt documentation) and override QWidget::onEnter() and QWidget::onLeave().

You will need to create a custom button class inheriting from QPushButton. You can define signals for mouseEnter and mouseLeave in your custom class and emit them from the onEnter() and onLeave() methods that you need to override.

查看更多
来,给爷笑一个
5楼-- · 2019-01-19 06:34

You can use QWidget::enterEvent ( QEvent * event ) for this.

You override this event and send a custom defined signal when ever this event occurs.

First you have to enable mouse tracking for this widget (setMouseTracking(true) in the constructor for example).

Header file:

class my_button
{
    // ...

protected:
    virtual void enterEvent( QEvent* e );

public Q_SIGNALS:
    void hovered();

    // ...
};

Source file:

void my_button::enterEvent( QEvent* e )
{
    Q_EMIT hovered();

    // don't forget to forward the event
    QWidget::enterEvent( e );
}

Where you use your button:

connect( one_of_my_button, SIGNAL(hovered()), this, SLOT(do_something_when_button_hovered()) );
查看更多
登录 后发表回答