Frage

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.

War es hilfreich?

Lösung

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

Andere Tipps

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();
    [..]
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top