Qt懸浮窗實現
曾經嘗試用鼠標事件’ void mousePressEvent(QMouseEvent *event);'實現,但是鼠標離開控件的行爲比較難監控
下面的方法比較簡單
- 用事件過濾器實現
- 進入控件時自動浮現
- 離開控件時自動關閉
bool eventFilter(QObject *watched, QEvent *event);
bool RecentDataItem::eventFilter(QObject *watched, QEvent *event)
{
qDebug()<<__PRETTY_FUNCTION__<<endl;
if(this == watched ) {
if(QEvent::Enter == event->type()) {
//鼠標進入
if(infodialog_float==nullptr){
infodialog_float=new InfoDialog();//一個自定義全局變量相當於QWidget
QPoint point = QCursor::pos();
point.rx() = point.x() + 100 ;
point.ry() = point.y() ;
infodialog_float->move(point);
infodialog_float->SetInfo(dataentry_in);
infodialog_float->setWindowFlags(Qt::FramelessWindowHint);
infodialog_float->raise();
infodialog_float->show();
return true;
}
}
else if (QEvent::Leave == event->type()) {
//鼠標離開
if(infodialog_float!=nullptr){
delete infodialog_float;
infodialog_float=nullptr;
return true;
}
}
}
return QWidget::eventFilter(watched, event);
}
- 安裝時間過濾器
this->setMouseTracking(true);
this->installEventFilter(this);