protected: bool eventFilter(QObject *obj, QEvent *event);
...ui->label_1->installEventFilter(this);... bool MainWindow::eventFilter(QObject *obj, QEvent *event) { if (obj == ui->label_1) { if (event->type() == QEvent::MouseMove ) { return true; ui->label_1->setStyleSheet("color: rgb(21, 103, 255)"); } else { return false; } } }
... if (event->type() == QEvent::MouseMove ) { return true; ui->label_1->setStyleSheet("color: rgb(21, 103, 255)"); }...
C++ (Qt)Test::Test(QWidget *parent) : QWidget(parent){ QHBoxLayout *hbl = new QHBoxLayout(this); l = new QLabel; l->setMouseTracking(true); l->installEventFilter(this); hbl->addWidget(l);} bool Test::eventFilter(QObject *o, QEvent *e){ if (o == l) { if (e->type() == QEvent::MouseButtonPress) { l->setStyleSheet("QLabel {background: red}"); } else if (e->type() == QEvent::MouseMove) { l->setStyleSheet("QLabel {background: blue}"); } } return QWidget::eventFilter(o, e);}
if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_Enter) {...}}