Search code examples
pythonpyqtpyqt5qcombobox

QComboBox setMaxVisible() doesn't work with fusion style


I have been teaching myself how to use python and PyQt5 to make a UI. The Fusion style looked really nice but I noticed that when I apply that style to an app, the QComboBox command setMaxVisibleItems no longer works. Instead, the fusion style QComboBox displays all items at once (or as many items as the screen size will allow) even when the setMaxVisibleItems is applied.

I thought maybe I was using the command wrong so I removed the fusion style and tried to set the max visible items with multiple different values. Each worked fine so I'm sure it must be the fusion style itself. Is there any way to change how the fusion style works or force it to apply setMaxVisibleItems? I've included some example code for it below.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QComboBox, QPushButton

class Example(QMainWindow):

    def __init__(self):
        super().__init__()

        combo = QComboBox(self)
        counter = 1
        while (counter < 21):
            combo.addItem(str(counter))
            counter = counter + 1
        combo.setMaxVisibleItems(5)

        combo.move(50, 50)

        self.qlabel = QLabel(self)
        self.qlabel.move(50,16)

        combo.activated[str].connect(self.onChanged)      

        self.setGeometry(50,50,320,200)
        self.setWindowTitle("QLineEdit Example")
        self.show()

    def onChanged(self, text):
        self.qlabel.setText(text)
        self.qlabel.adjustSize()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    #app.setStyle("fusion")
    ex = Example()
    sys.exit(app.exec_())

Applying the fusion style means the application shows all 20 items at once. Commenting out the fusion style means the application shows 5 items at a time.


Solution

  • The maxVisibleItems property is not respected by all styles.

    Note: This property is ignored for non-editable comboboxes in styles that returns true for QStyle::SH_ComboBox_Popup such as the Mac style or the Gtk+ Style.

    Note that if your combobox were editable, it would probably work as expected. The way styles behave is for being able to consistently match the native behavior they are trying to mimic. I don't know the reason for Fusion not to adhere to maxVisibleItems.

    You can always create your own style–based on Fusion–to change a specific behavior. In general it is advised to respect the user's expectance of native styling (or the style they configured), and not to manually set a style.