Search code examples
pythonqtpyqtqcomboboxqdialog

How to stick widgets side by side


The code below creates a dialog window with three widgets: QLabel, QComboBox and QButton.

I want QLabel and QComboBox to be sitting on a same line. That is why both of these widgets are assigned to the same horizontal layout. Resizing the dialog creates a huge empty space between the Label and ComboBox. How to assure that the left side of the Combo sticks to the right side of Label when dialog is resizing?

enter image description here

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
app = QApplication([])


class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setLayout(QVBoxLayout())
        h_layout = QHBoxLayout()
        self.layout().addLayout(h_layout)
        label = QLabel(self)
        label.setText('Month:')
        combo = QComboBox(self)
        h_layout.addWidget(label)
        h_layout.addWidget(combo)
        button = QPushButton('Ok')
        self.layout().addWidget(button)
        self.resize(200, 50)
        self.show()


dialog = Dialog()
app.exec_()

Solution

  • You have to establish the size policy through QSizePolicy, in your case you must set the policy QSizePolicy::Expanding in the horizontal component of the QComboBox:

    import sys
    
    from PyQt5.QtGui import *
    from PyQt5.QtWidgets import *
    from PyQt5.QtCore import *
    
    app = QApplication(sys.argv)
    
    
    class Dialog(QDialog):
        def __init__(self, parent=None):
            super(Dialog, self).__init__(parent)
            self.setLayout(QVBoxLayout())
            h_layout = QHBoxLayout()
            self.layout().addLayout(h_layout)
            label = QLabel(self)
            label.setText('Month:')
    
            combo = QComboBox(self)
            policy = combo.sizePolicy()
            policy.setHorizontalPolicy(QSizePolicy.Expanding)
            combo.setSizePolicy(policy)
    
            h_layout.addWidget(label)
            h_layout.addWidget(combo)
            button = QPushButton('Ok')
            self.layout().addWidget(button)
            self.resize(200, 50)
            self.show()
    
    
    dialog = Dialog()
    sys.exit(app.exec_())
    

    enter image description here