2012-07-06 50 views
0

我有以下pyside部件代碼:pyside QT4,alligningment語法誤解

class NavigationHeadWidget(QWidget): 
    def __init__(self): 
     QWidget.__init__(self) 

     self._current_page = 0 
     self._last_page = 0 

     self._pageination_string = "page %s of %s" 
     self._pagination_label = QLabel() 
     self._pagination_label.setText(self._pageination_string % (str(self._current_page), str(self._last_page))) 


     self.setMinimumWidth(400) 
     self._header_buttons_prev = QPushButton("b_prev") 
     self._header_buttons_next = QPushButton("b_next") 
     self._header_buttons_prev.setText("prev") 
     self._header_buttons_next.setText("next") 
     self._header_buttons_next.setMaximumWidth(40) 
     self._header_buttons_prev.setMaximumWidth(40) 
     self._layout = QHBoxLayout() 
     self._layout.addWidget(self._header_buttons_prev,Qt.AlignLeft) 
     self._layout.addWidget(self._pagination_label,Qt.AlignCenter) 
     self._layout.addWidget(self._header_buttons_next,Qt.AlignRight) 
     self.setLayout(self._layout) 

導致:

enter image description here

我希望文字的按鈕之間的中心,但它留下alligns。

如果我註釋掉的標籤,我得到:

enter image description here

我希望留在按鈕和右神韻:,但他們似乎並沒有這樣做。

什麼是正確的語法來獲得我想要的行爲?

另外我如何讓按鈕自動調整到它包含的文本的大小?必須在上面的代碼中硬編碼大小。

回答

2

您正在添加標籤,它居中(它填充了兩個按鈕之間的所有空間)。但這並不意味着標籤內的文字也會自動居中。要做到這一點,只需添加:

self._pagination_label.setAlignment(Qt.AlignCenter) 

您還可以添加的按鈕和標籤來獲得同樣的效果之間QSpacerItem S(通過調用佈局的addStretch方法,你需要具有伸縮性的空間):

self._layout.addWidget(self._header_buttons_prev) 
self._layout.addStretch() 
self._layout.addWidget(self._pagination_label) 
self._layout.addStretch() 
self._layout.addWidget(self._header_buttons_next) 
+0

謝謝。我是否也按照相同的按鈕來讓他們行爲? :D – 2012-07-06 15:06:31

+0

我已經擴展了我的答案,詳細介紹了使用墊片的情況。這樣,無論標籤是否存在,按鈕始終保持左/右對齊。 – mata 2012-07-06 15:28:17