PyQt5 - Adding border to the editable ComboBox

PyQt5 - Adding border to the editable ComboBox

To add a border to the editable portion of a QComboBox, you'd want to target the line edit component of the QComboBox using stylesheets. Here's how you can achieve that:

import sys from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QComboBox class AppDemo(QWidget): def __init__(self): super().__init__() self.resize(400, 300) layout = QVBoxLayout() combobox = QComboBox() combobox.setEditable(True) combobox.addItems(['Option 1', 'Option 2', 'Option 3']) # Set the style for the combobox's line edit combobox.setStyleSheet(""" QComboBox:editable { background: white; border: 2px solid red; } QComboBox:!editable, QComboBox::drop-down:editable { background: transparent; } QComboBox:!editable:on, QComboBox::drop-down:editable:on { background: transparent; } QComboBox:on { /* shift the text when the popup opens */ padding-top: 3px; padding-left: 4px; } QComboBox::drop-down { subcontrol-origin: padding; subcontrol-position: top right; width: 15px; border-left-width: 0px; border-left-color: transparent; border-left-style: solid; /* just a single line */ border-top-right-radius: 3px; /* same radius as the QComboBox */ border-bottom-right-radius: 3px; } """) layout.addWidget(combobox) self.setLayout(layout) if __name__ == '__main__': app = QApplication(sys.argv) demo = AppDemo() demo.show() sys.exit(app.exec_()) 

Here's what we did:

  1. We set the QComboBox to be editable using setEditable(True).
  2. Using stylesheets, we specifically target the QComboBox:editable pseudo-state, which affects the editable portion (the line edit component) of the combo box. We set its background to white and added a 2px solid red border.
  3. The other parts of the stylesheet are related to keeping a consistent appearance for the combobox when it's not in editable mode and managing the appearance of the drop-down arrow.

You can, of course, adjust the styles as per your design needs.


More Tags

java-http-client purrr associative-array continuous-deployment payment liquid unique-id git-fetch android-media3 input-field

More Programming Guides

Other Guides

More Programming Examples