QT 事件过滤器实现鼠标悬浮时两个按钮背景互换

假设我们在一个 Dialog 中放置了两个 PushButton ,分别叫 pushButton 和 pushButton_2。

要实现功能:

  • 当鼠标悬浮到其中一个pushButton上时,两个pushbutton的QSS样式互换

newdialog.h

class newDialog : public QDialog
{
    ...
    代码省略
    ...
public:
    //自定义函数,用来注册需要管理的对象
    void toInstallEventFilter(); 
    //用来处理需要管理的对象的事件
    bool eventFilter(QObject *target, QEvent *event);
    ...
    代码省略
    ...
};

newdialog.cpp

//构造函数
newDialog::newDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::newDialog)
{
    ui->setupUi(this);
    //在构造函数中调用自定义函数 toInstallEventFilter()
    toInstallEventFilter();
}

//自定义函数
void newDialog::toInstallEventFilter()
{
    ui->pushButton->installEventFilter(this);
    ui->pushButton_2->installEventFilter(this);
}

//事件过滤器函数
bool newDialog::eventFilter(QObject *target, QEvent *event)
{
    if(target == ui->pushButton)
    {
        if(event->type() == QEvent::Enter)
        {
            ui->pushButton->setStyleSheet("QPushButton#pushButton{background-color: rgb(46, 52, 54);}");
            ui->pushButton_2->setStyleSheet("QPushButton#pushButton_2{background-color: rgb(238, 238, 236);}");
        }
        ui->pushButton->show();
        ui->pushButton_2->show();
    }
    if(target == ui->pushButton_2)
    {
        if(event->type() == QEvent::Enter)
        {
            ui->pushButton_2->setStyleSheet("QPushButton#pushButton_2{background-color: rgb(46, 52, 54);}");
            ui->pushButton->setStyleSheet("QPushButton#pushButton{background-color: rgb(238, 238, 236);}");
        }
        ui->pushButton->show();
        ui->pushButton_2->show();
    }

    return QDialog::eventFilter(target, event);
}

示例(截图中没有鼠标指针标志,实际上是有的):
当鼠标悬浮在左pushButton时:
这里写图片描述
当鼠标悬浮在右pushButton时:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/baishuiniyaonulia/article/details/81273582