eventFilter(QObject *obj, QEvent *e) 没有检测到正确的对象
eventFilter(QObject *obj, QEvent *e) does not detect right object
我希望我的程序在我的鼠标位于 labelname
(一个 QLabel
)时打印 "mouse on label name",而在我的鼠标不在时打印 "mouse not on label name"位于 labelname
.
即使我将鼠标放在 labelname
上,我的程序也会打印 "mouse not on label name"。
我怎么知道鼠标不在 labelname
上?
bool Dialog::eventFilter(QObject *obj, QEvent *e)
{
if(qobject_cast<QLabel*>(obj) == ui->labelname) {
cout << “mouse on label name” << endl;
}else if(qobject_cast<QLabel*>(obj) != ui->labelname) {
cout << “mouse not on label name” << endl;
}
return false;
}
确保您正在安装指示鼠标已进入或离开小部件的 event filter correctly. Also, if you want to track mouse position you have to enable mouseTracking
, otherwise the move events won't be triggered (though QEvent::Enter
and QEvent::Leave
will, which are the ones。
这里是一个简单的操作示例:
MyWidget::MyWidget(QWidget *parent)
: QWidget(parent)
{
m_label = new QLabel("Hello world!");
m_label->setObjectName("m_label");
m_label->installEventFilter(this);
m_label->setMouseTracking(true);
auto hlayout = new QVBoxLayout();
hlayout->addWidget(m_label);
setLayout(hlayout);
}
bool MyWidget::eventFilter(QObject* sender, QEvent* event)
{
if (sender == m_label) {
qDebug() << sender->objectName() << event->type();
if (event->type() == QEvent::Enter) {
qDebug() << "mouse on label name";
} else if (event->type() == QEvent::Leave) {
qDebug() << "mouse not on label name";
}
}
return QWidget::eventFilter(sender, event);
}
GitHub 中提供了完整的工作示例。
我希望我的程序在我的鼠标位于 labelname
(一个 QLabel
)时打印 "mouse on label name",而在我的鼠标不在时打印 "mouse not on label name"位于 labelname
.
即使我将鼠标放在 labelname
上,我的程序也会打印 "mouse not on label name"。
我怎么知道鼠标不在 labelname
上?
bool Dialog::eventFilter(QObject *obj, QEvent *e)
{
if(qobject_cast<QLabel*>(obj) == ui->labelname) {
cout << “mouse on label name” << endl;
}else if(qobject_cast<QLabel*>(obj) != ui->labelname) {
cout << “mouse not on label name” << endl;
}
return false;
}
确保您正在安装指示鼠标已进入或离开小部件的 event filter correctly. Also, if you want to track mouse position you have to enable mouseTracking
, otherwise the move events won't be triggered (though QEvent::Enter
and QEvent::Leave
will, which are the ones。
这里是一个简单的操作示例:
MyWidget::MyWidget(QWidget *parent)
: QWidget(parent)
{
m_label = new QLabel("Hello world!");
m_label->setObjectName("m_label");
m_label->installEventFilter(this);
m_label->setMouseTracking(true);
auto hlayout = new QVBoxLayout();
hlayout->addWidget(m_label);
setLayout(hlayout);
}
bool MyWidget::eventFilter(QObject* sender, QEvent* event)
{
if (sender == m_label) {
qDebug() << sender->objectName() << event->type();
if (event->type() == QEvent::Enter) {
qDebug() << "mouse on label name";
} else if (event->type() == QEvent::Leave) {
qDebug() << "mouse not on label name";
}
}
return QWidget::eventFilter(sender, event);
}
GitHub 中提供了完整的工作示例。