I created a GUI width Qt Creator (Qt 5.0.1), of course also making use of layouts. For aesthetical reasons, I would like a QPushButton to be of the same width as another QPushButton placed in some other corner of the GUI. This other button changes the size dynamically when changing the window size, which is desired behavior.

Is there a way to (dynamically) link the sizes of these buttons without changing the layouts? If possible I'd like to avoid fixed sizes.

有帮助吗?

解决方案

You can override the resizeEvent of first and send signal(with size) to second.

其他提示

I would propose the following solution (without sub-classing button class). Actually the code bellow can be used for synchronizing of any widgets, not only QPushButtons.

The SizeSynchronizer class:

/// 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;
};

Simple demonstration of class usage - synchronize two buttons:

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();
    [..]
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top