Hassan Syed
Hassan Syed

Reputation: 20485

pyside qt4, alligningment syntax misunderstanding

I have the following pyside widget code :

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)

which results in :

enter image description here

I expect the text to centre between the buttons, but it left alligns.

If I comment out the label I get :

enter image description here

I expect the buttons to be left and right alligned, but they don't seem to do that.

Whats the correct syntax to get the behaviour I want ?

Additionaly How do I get the button to size automatically to the text it contains ? Having to hardcode the size in the code above.

Upvotes: 0

Views: 518

Answers (1)

mata
mata

Reputation: 69012

You'r adding the label, and it's centered (it fills all the space between the two buttons). But that doesn't mean that text within the label is also centered automatically. To do that, just add:

self._pagination_label.setAlignment(Qt.AlignCenter)

You can also add QSpacerItems between the buttons and the label to get the same effect (by calling the layout's addStretch method where you need a stretchable space):

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)

Upvotes: 2

Related Questions