PyQt5 QComboBox - Change border style when it is non-editable and get pressed

PyQt5 QComboBox - Change border style when it is non-editable and get pressed

To change the border style of a non-editable QComboBox when it's pressed, you'll need to use stylesheets.

Here's a step-by-step example:

  • Basic Setup: First, set up a simple QComboBox inside a PyQt5 application:
import sys from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QComboBox class ComboBoxApp(QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): layout = QVBoxLayout() self.combo = QComboBox(self) self.combo.addItems(["Option 1", "Option 2", "Option 3"]) layout.addWidget(self.combo) self.setLayout(layout) self.setWindowTitle('QComboBox Border Style Example') self.show() app = QApplication(sys.argv) window = ComboBoxApp() sys.exit(app.exec_()) 
  • Style the QComboBox: Update the border style for the non-editable QComboBox when pressed:
self.combo.setStyleSheet(""" QComboBox:!editable:!pressed { border: 1px solid black; } QComboBox:!editable:pressed { border: 2px solid red; } """) 

Here's a brief explanation of the stylesheet:

  • QComboBox:!editable:!pressed: Targets a QComboBox that is NOT editable and NOT pressed.
  • QComboBox:!editable:pressed: Targets a QComboBox that is NOT editable but is pressed.

With the updated stylesheet:

class ComboBoxApp(QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): layout = QVBoxLayout() self.combo = QComboBox(self) self.combo.addItems(["Option 1", "Option 2", "Option 3"]) # Applying the stylesheet to the QComboBox self.combo.setStyleSheet(""" QComboBox:!editable:!pressed { border: 1px solid black; } QComboBox:!editable:pressed { border: 2px solid red; } """) layout.addWidget(self.combo) self.setLayout(layout) self.setWindowTitle('QComboBox Border Style Example') self.show() app = QApplication(sys.argv) window = ComboBoxApp() sys.exit(app.exec_()) 

Now, when you run the code, the border of the QComboBox will change to red and become thicker when pressed.


More Tags

npapi mysql-error-1093 private preloader viewdidload otool okhttp file-handling wildfly parseexception

More Programming Guides

Other Guides

More Programming Examples