我創建了一個GUI寬度Qt創建者(Qt的5.0.1),當然還利用佈局。對於美學原因,我想一個QPushButton是相同寬度的作爲另一QPushButton放置在GUI的一些其它角。這個其他按鈕在更改窗口大小時動態更改大小,這是期望的行爲。鏈路QPushButton寬度到另一個QPushButton
有沒有一種辦法(動態)鏈接這些按鈕的尺寸不改變佈局?如果可能的話,我想避免固定大小。
我創建了一個GUI寬度Qt創建者(Qt的5.0.1),當然還利用佈局。對於美學原因,我想一個QPushButton是相同寬度的作爲另一QPushButton放置在GUI的一些其它角。這個其他按鈕在更改窗口大小時動態更改大小,這是期望的行爲。鏈路QPushButton寬度到另一個QPushButton
有沒有一種辦法(動態)鏈接這些按鈕的尺寸不改變佈局?如果可能的話,我想避免固定大小。
您可以覆蓋第一的resizeEvent和發送信號(與大小)至第二。
我建議以下解決方案(無子類按鈕類)。實際上,下面的代碼可以用於同步任何小部件,而不僅僅是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();
[..]
}
我希望有更多的「內置」的解決方案,但最後我做到了正如你所建議的那樣,它工作正常。 – Chris