Search code examples
pythonpyqtqcombobox

How to reduce the size of a QComboBox with PyQt?


I created a small program with PyQt in which I put a QComboBox, but this one contains only a list of 2 letters. The program window being small, to save space, I would like to reduce the width of the QComboBox.

This is what it looks like now. The width is too large.

This is what it looks like now. The width is too large.

I searched the internet, but after a lot of searching time, I still haven't found anything. Thank you in advance if you have an idea.


Solution

  • There are several methods to resize a widget's size. Lets say the QComboBox is defined as this:

    combo = QComboBox(self)
    

    One way is to use QWidget.resize(width, height)

    combo.resize(200,100)
    

    To obtain a proper size automatically, you can use QWidget.sizeHint() or sizePolicy()

    combo.resize(combo.sizeHint())
    

    If you want to set fixed size, you can use setFixedSize(width, height), setFixedWidth(width), or setFixedHeight(height)

    combo.setFixedSize(400,100)
    combo.setFixedWidth(400)
    combo.setFixedHeight(100)
    

    Here's an example:

    enter image description here

    from PyQt5.QtWidgets import (QWidget, QLabel, QComboBox, QApplication)
    import sys
    
    class ComboboxExample(QWidget):
        def __init__(self):
            super().__init__()
    
            self.label = QLabel("Ubuntu", self)
    
            self.combo = QComboBox(self)
            self.combo.resize(200,25)
            # self.combo.resize(self.combo.sizeHint())
            # self.combo.setFixedWidth(400)
            # self.combo.setFixedHeight(100)
            # self.combo.setFixedSize(400,100)
            self.combo.addItem("Ubuntu")
            self.combo.addItem("Mandriva")
            self.combo.addItem("Fedora")
            self.combo.addItem("Arch")
            self.combo.addItem("Gentoo")
    
            self.combo.move(25, 25)
            self.label.move(25, 75)
    
            self.combo.activated[str].connect(self.onActivated)        
    
            # self.setGeometry(0, 0, 500, 125)
            self.setWindowTitle('QComboBox Example')
            self.show()
    
        def onActivated(self, text):
            self.label.setText(text)
            self.label.adjustSize()  
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        ex = ComboboxExample()
        sys.exit(app.exec_())