PyQt5 QComboBox - Change border style when it non-editable and on state

PyQt5 QComboBox - Change border style when it non-editable and on state

If you want to customize the border style of a QComboBox based on its editability and its state (e.g., normal, hover, pressed), you can use the Qt stylesheet mechanism. The Qt stylesheet allows you to style widgets in a manner similar to CSS.

Here's an example showing how to set different border styles for a non-editable QComboBox in different states:

import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QComboBox, QWidget class ComboBoxDemo(QMainWindow): def __init__(self): super().__init__() self.central_widget = QWidget(self) self.layout = QVBoxLayout(self.central_widget) self.combobox = QComboBox(self.central_widget) for i in range(5): self.combobox.addItem(f"Item {i}") # Make the combobox non-editable self.combobox.setEditable(False) # Set stylesheet to change border based on state self.combobox.setStyleSheet(""" QComboBox:!editable { border: 2px solid green; /* Normal state */ } QComboBox:!editable:hover { border: 2px solid blue; /* Hover state */ } QComboBox:!editable:on { /* drop-down arrow clicked */ border: 2px solid red; /* On state (active) */ } QComboBox:!editable:disabled { border: 2px solid grey; /* Disabled state */ } """) self.layout.addWidget(self.combobox) self.setCentralWidget(self.central_widget) app = QApplication(sys.argv) mainWin = ComboBoxDemo() mainWin.show() sys.exit(app.exec_()) 

In the above example, we're styling the QComboBox based on its state:

  • Normal state: Green border
  • Hover state: Blue border
  • Active (when the drop-down arrow is clicked): Red border
  • Disabled state: Grey border

The :!editable pseudo-state is used to ensure the styles only apply when the QComboBox is non-editable.

Note that while stylesheets are powerful and provide a lot of flexibility, using them can sometimes override the native look-and-feel of widgets, so always check the appearance on the platforms you're targeting.


More Tags

unc spring-jms react-leaflet defaultmodelbinder angular-template shader jmeter-3.2 telephonymanager amazon-redshift-spectrum export

More Programming Guides

Other Guides

More Programming Examples