QWidget有窗口属性设置函数:
void setWindowFlags(Qt::WindowFlags type)
一般调用这个函数即可让窗口置顶显示
QWidget* pWidget = new QWidget();
pWidget->setWindowFlags(pWidget->windowFlags() | Qt::WindowStaysOnTopHint)
但是注意看setWindowFlags()函数的说明文档:
Note: This function calls setParent() when changing the flags for a window, causing the widget to be hidden. You must call show() to make the widget visible again..
没错,这个函数会调用setParent()并且隐藏窗口,然后需要你重新调用show()将窗口设置为可见。这就导致置顶过程中窗口会闪烁一下!
看一下setWindowFlags() 的实现:
void QWidgetPrivate::setWindowFlags(Qt::WindowFlags flags)
{
Q_Q(QWidget);
if (q->data->window_flags == flags)
return;
if ((q->data->window_flags | flags) & Qt::Window) {
// the old type was a window and/or the new type is a window
QPoint oldPos = q->pos();
bool visible = q->isVisible();
const bool windowFlagChanged = (q->data->window_flags ^ flags) & Qt::Window;
q->setParent(q->parentWidget(), flags);
// if both types are windows or neither of them are, we restore
// the old position
if (!windowFlagChanged && (visible || q->testAttribute(Qt::WA_Moved)))
q->move(oldPos);
// for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
adjustQuitOnCloseAttribute();
} else {
q->data->window_flags = flags;
}
}
确实,对QWidget的私类调用了setParent方法,估计QT开发人员也是为了偷懒,不想重写一个专门设置flags的方法,而是通过setParent()间接设置了flags,parentWidget()还是原来的parentWidget()!
解决方法
获取QWidget的window,再对window设置置顶属性!
QWidget* pWidget = new QWidget();
QWindow* pWin = pWidget->windowHandle();
pWin->setFlags(pWidget->windowFlags() | Qt::WindowStaysOnTopHint)
---完美无闪烁!^_^