2013-09-27 36 views
0

我創建了一個GUI寬度Qt創建者(Qt的5.0.1),當然還利用佈局。對於美學原因,我想一個QPushButton是相同寬度的作爲另一QPushButton放置在GUI的一些其它角。這個其他按鈕在更改窗口大小時動態更改大小,這是期望的行爲。鏈路QPushButton寬度到另一個QPushButton

有沒有一種辦法(動態)鏈接這些按鈕的尺寸不改變佈局?如果可能的話,我想避免固定大小。

回答

2

您可以覆蓋第一的resizeEvent和發送信號(與大小)至第二。

+0

我希望有更多的「內置」的解決方案,但最後我做到了正如你所建議的那樣,它工作正常。 – Chris

0

我建議以下解決方案(無子類按鈕類)。實際上,下面的代碼可以用於同步任何小部件,而不僅僅是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(); 
    [..] 
} 
+0

非常感謝您的建議!我嘗試了你的代碼,但不幸的是它不工作。我在eventFilter方法中放置了一個qDebug輸出,並且發現它在調整窗口大小時不會被調用。我使用窗體編輯器創建了GUI,這可能是一個原因嗎? – Chris

+0

你把它安裝了嗎(事件過濾器)到右邊的按鈕? – vahancho

+0

是的,我做到了,即使錯了按鈕,我應該看到調試出來,因爲改變窗口大小時,所有按鍵得到重新調整大小... – Chris