【问题标题】:Automatically hiding a Qt QWidget after the user clicks elsewhere用户点击别处后自动隐藏 Qt QWidget
【发布时间】:2021-10-15 16:59:29
【问题描述】:

我想创建一个类似于弹出窗口的QWidget,但我不知道该怎么做。

我想创建一个边栏/抽屉,当用户单击按钮时会显示它。用户将与侧边栏的子小部件进行短暂交互。棘手的部分是,当用户单击应用程序中的其他位置时,我希望侧边栏自动隐藏。最坏的情况我可以要求用户手动切换侧边栏,但自动隐藏它很方便。

我尝试或调查过:

  • Setting the Qt::Popup window flag,但侧边栏需要是一个小部件,而不是一个单独的窗口。
  • 监听焦点事件,但我想支持键盘导航。用户应该能够在侧边栏保持可见的情况下切换到其他小部件。当用户实际与其他小部件交互(例如按 Enter)时,侧边栏应隐藏。
  • 在顶级小部件上添加事件过滤器,但它不接收在其子级上发生的事件(例如单击按钮)。
  • 在应用程序的其余部分添加一个不可见的“覆盖”小部件,但我希望用户能够直接单击其他小部件。在不可见的叠加层中捕获点击需要用户点击两次(一次清除叠加层,然后再次与其他小部件交互)。

这不可行吗?

【问题讨论】:

标签: qt


【解决方案1】:

一种可能是在QApplication 实例本身上安装一个事件过滤器。但请注意,应用程序范围的事件过滤器可能会对性能产生显着影响,因此仅应在必要时安装它。模型可能看起来像...

class sidebar: public QWidget {
    using super = QWidget;
protected:
    virtual bool eventFilter (QObject *obj, QEvent *event) override
        {

            /*
             * Your stuff goes here...
             */
            if (auto *widget = dynamic_cast<QWidget *>(obj)) { 
                if (isAncestorOf(widget)) {

                    /*
                     * obj refers to a QWidget of some description that is
                     * a child of this sidebar instance.
                     */
                } else {

                    /*
                     * widget _isn't_ a child of this sidebar so may need
                     * to take action (including hiding) depending on the
                     * specifics of widget and the event details.
                     */
                }
            }
            return super::eventFilter(obj, event);
        }
    virtual void showEvent (QShowEvent *event) override
        {
            super::showEvent(event);
            qApp->installEventFilter(this);
        }
    virtual void hideEvent (QHideEvent *event) override
        {
            super::hideEvent(event);
            qApp->removeEventFilter(this);
        }
};

显然需要一定数量的实验:-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-30
    • 2017-06-05
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多