原文链接:https://blog.csdn.net/yangyang031213/article/details/78584108
为了尝试得到Qt窗口得到或者失去焦点的事件,使用了两种方法尝试:
方法一:重载窗口的 focusInEvent 和 focusOutEvent。
.h
protected:
virtual void focusInEvent(QFocusEvent * event);
virtual void focusOutEvent(QFocusEvent * event);
.cpp
void ShapeWindow::focusInEvent(QFocusEvent *)
{
qDebug()<<"show";
show();
}
void ShapeWindow::focusOutEvent(QFocusEvent *)
{
qDebug()<<"hide";
hide();
}
方法二:使用 eventFilter 过滤。
.h
public slots:
bool eventFilter(QObject *watched, QEvent *event);
public slots:
bool eventFilter(QObject *watched, QEvent *event);
.cpp
初始化时安装事件过滤:
ui->widget_shape->installEventFilter(this);
ui->widget_thick->installEventFilter(this);
过滤函数:
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
qDebug()<<"eventFilter"<<event->type()<<endl;
if(watched == ui->widget_shape)
{
qDebug()<<"eventFilter widget_shape "<<event->type()<<endl;
if(event->type() == QEvent::FocusIn)
{
qDebug()<<"eventFilter widget_shape FocusIn"<<endl;
;
}
else if(event->type() == QEvent::FocusOut)
{
qDebug()<<"eventFilter widget_shape FocusOut"<<endl;
ui->widget_shape->hide();
}
}
else if(watched == ui->widget_thick)
{
qDebug()<<"eventFilter widget_thick "<<event->type()<<endl;
if(event->type() == QEvent::FocusIn)
{
qDebug()<<"eventFilter widget_thick FocusIn"<<endl;
;
}
else if(event->type() == QEvent::FocusOut)
{
qDebug()<<"eventFilter widget_thick FocusOut"<<endl;
ui->widget_thick->hide();
}
}
return QMainWindow::eventFilter(watched,event);
}
widget默认是没有焦点的,此时使用上边两种方法都无法获取到焦点事件,需要设置窗口的 focusPolicy 属性,并在widget显示之后 setFocus()
void MainWindow::on_btn_thick_clicked() //粗细
{
ui->widget_shape->hide();
ui->widget_thick->show();
ui->widget_thick->setFocus();
}