QWidget窗口置顶闪烁问题

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)

---完美无闪烁!^_^

  • 14
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值