初始化UI时我调用了QDialogButtonBox类的clear函数,代码如下:
if (this->_iconBtnBox2->buttons().count() > 0)
{
bLostFocus = false;//Add by zxb for _iconBtnBox2清除其所含按钮时会发出丢失焦点的QFocusEvent
this->_iconBtnBox2->clear();
}
另外为QDialogButtonBox中包含的每个按钮要处理的事件添加了如下代码:
for(int i=0; i!=_iconBtnBox2->buttons().size(); ++i)
{
_iconBtnBox2->buttons().at(i)->installEventFilter(this);
}
处理事件的函数代码如下:
bool DeskWidget3::eventFilter(QObject *target, QEvent *event)
{
QFocusEvent *focusEvent = static_cast<QFocusEvent *>(event);
if (focusEvent->gotFocus())
{
QAbstractButton *button = (QAbstractButton *)target;
int index = _iconBtnBox2->buttons().indexOf(button);
APPINFO *info = (list->at(index));
button->setStyleSheet(QString("background-image: url(")+"/resource/resource/dock/desktop/"+info->ciconFile()+");");
}
if (focusEvent->lostFocus())
{
if (bLostFocus)//Add by zxb for _iconBtnBox2清除其所含按钮时会发出丢失焦点的QFocusEvent
{
QAbstractButton *button = (QAbstractButton *)target;
int index = _iconBtnBox2->buttons().indexOf(button);
APPINFO *info = (list->at(index));
button->setStyleSheet(QString("background-image: url(")+"/resource/resource/dock/desktop/"+info->iconFile()+");");
}
else
bLostFocus = true;//Add by zxb for _iconBtnBox2清除其所含按钮时会发出丢失焦点的QFocusEvent
}
return QWidget::eventFilter(target, event);
}
编译运行,每次更新QDialogButtonBox包含的按钮时都会导致程序崩溃。添加打印信息后才发觉调用QDialogButtonBox类的clear函数时会发出QFocusEvent的丢失焦点事件。故上面的代码中用变量来控制是否处理按钮的丢失焦点事件。