【问题标题】:link QPushButton width to another QPushButton将 QPushButton 宽度链接到另一个 QPushButton
【发布时间】:2013-09-27 07:39:34
【问题描述】:

我创建了一个 GUI 宽度 Qt Creator (Qt 5.0.1),当然也使用了布局。出于美学原因,我希望 QPushButton 与放置在 GUI 其他角落的另一个 QPushButton 具有相同的宽度。当更改窗口大小时,此另一个按钮会动态更改大小,这是所需的行为。

有没有办法(动态地)链接这些按钮的大小而不改变布局?如果可能的话,我想避免固定尺寸。

【问题讨论】:

    标签: c++ qt qpushbutton


    【解决方案1】:

    您可以覆盖第一个的resizeEvent并将信号(带大小)发送到第二个。

    【讨论】:

    • 我希望有一个更“内置”的解决方案,但最后我按照你的建议做了,效果很好。
    【解决方案2】:

    我会提出以下解决方案(没有子分类按钮类)。实际上下面的代码可以用于同步任何小部件,不仅仅是QPushButtons

    SizeSynchronizer 类:

    /// Synchronizes the given widget's size with other's - one that the SizeSynchronizer installed on.
    class SizeSynchronizer : public QObject
    {
    public:
        SizeSynchronizer(QWidget *w)
            :
                m_widget(w)
        {}
    
        bool eventFilter(QObject *obj, QEvent *ev)
        {
            if (m_widget) {
                if (ev->type() == QEvent::Resize) {
                    QResizeEvent *resizeEvent = static_cast<QResizeEvent *>(ev);
                    m_widget->resize(resizeEvent->size());
                }
            }
            return QObject::eventFilter(obj, ev);
        }
    private:
        QWidget *m_widget;
    };
    

    类使用的简单演示——同步两个按钮:

    int main(int argc, char *argv[])
    {
        [..]
        // First button will be synchronized with the second one, i.e. when second
        // resized, the first one will resize too.
        QPushButton pb1("Button1");
        QPushButton pb2("Button2");
    
        // Create synchronizer and define the button that should be synchronized.
        SizeSynchronizer sync(&pb1);
        pb2.installEventFilter(&sync);
    
        pb2.show();
        pb1.show();
        [..]
    }
    

    【讨论】:

    • 非常感谢您的建议!我试过你的代码,但不幸的是它不起作用。我在 eventFilter 方法中放置了一个 qDebug 输出,我发现当我调整窗口大小时它不会被调用。我使用表单编辑器创建了 GUI,这可能是原因吗?
    • 是的,我做到了,即使使用了错误的按钮,我也应该看到调试结果,因为在更改窗口大小时所有按钮都会重新调整大小...
    • @Chris,“即使使用了错误的按钮,我也应该看到调试”——这不是真的。只有在调整安装事件过滤器的小部件大小时,您才会看到它。在我的示例代码中,当您调整“Button2”的大小时会发生这种情况。
    • 可能有误会,或者我没有正确表达自己。当我用鼠标重新调整窗口大小时,基本上所有按钮也会重新调整大小,因为它们是堆叠在布局中的。因此,当我使用窗口大小时,无论如何我都会看到一些东西。
    猜你喜欢
    • 1970-01-01
    • 2012-08-05
    • 2017-01-22
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多