PyQt5 - How to make text center align for non-editable ComboBox

PyQt5 - How to make text center align for non-editable ComboBox

In PyQt5, you can center align the text of a QComboBox by customizing the style of the items in the list. Unfortunately, QComboBox doesn't have a direct property to set the alignment of the display text when the combo box is non-editable. However, you can achieve this by setting a custom item delegate.

Here's a step-by-step example of how you can center align text in a non-editable QComboBox:

  1. Create a subclass of QStyledItemDelegate to customize the way items are displayed.
  2. Reimplement the paint method to draw the text centered.
  3. Set this custom delegate to the QComboBox.

Here's a sample implementation:

import sys from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QComboBox, QStyledItemDelegate from PyQt5.QtCore import Qt, QRect # Step 1: Create a custom delegate that centers text class CenteredItemDelegate(QStyledItemDelegate): def paint(self, painter, option, index): # Call the base class method to draw the background and focus rect super().paint(painter, option, index) # Get the text from the model text = index.data(Qt.DisplayRole) # Draw the text centered in the option.rect painter.drawText(QRect(option.rect), Qt.AlignCenter, text) # Step 2: Apply the delegate to your QComboBox class MyWidget(QWidget): def __init__(self): super().__init__() layout = QVBoxLayout(self) # Create the combo box and populate it with items self.comboBox = QComboBox() self.comboBox.addItems(["Item 1", "Item 2", "Item 3"]) # Make the combo box non-editable self.comboBox.setEditable(False) # Set the custom delegate self.comboBox.setItemDelegate(CenteredItemDelegate()) # Add the combo box to the layout layout.addWidget(self.comboBox) # Boilerplate code to run the application if __name__ == '__main__': app = QApplication(sys.argv) window = MyWidget() window.show() sys.exit(app.exec_()) 

In this code:

  • CenteredItemDelegate inherits from QStyledItemDelegate and reimplements the paint method to draw the text in the center of the provided rectangle (option.rect).
  • MyWidget sets up the UI with a QComboBox and applies the custom delegate to it.
  • self.comboBox.setEditable(False) ensures that the combo box is not editable, which is required for the custom delegate to take effect.

Run this code in a Python environment where PyQt5 is installed, and you should see a window with a combo box displaying centered items.


More Tags

git-revert querying outlook-2010 utf-8 ttk kendo-listview continuous-deployment associations right-align jpeg

More Programming Guides

Other Guides

More Programming Examples