推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
Henrysun
V2EX  ›  Python

请教一下各位佬, Pyqt5 中 QComboBox 选择框的文本怎么居中

  •  
  •   Henrysun · Feb 21, 2025 · 4575 views
    This topic created in 587 days ago, the information mentioned may be changed or developed.
    问了 gpt ,试了很多办法,目前只能让下拉选项居中,已选择的框始终不能居中
    iorilu
        1
    iorilu  
       Feb 21, 2025
    你文本前弄几个空格不行吗
    Henrysun
        2
    Henrysun  
    OP
       Feb 21, 2025   ❤️ 1
    找到办法了,通过重构 QComboBox 类实现。
    然后原本的 self.select_combo = QComboBox()改为重构后的 self.select_combo = CenteredComboBox()创建

    现提供给大家参考
    # --------------------------
    class CenteredComboBox(QComboBox):
    def paintEvent(self, event):
    painter = QStylePainter(self)
    option = QStyleOptionComboBox()
    self.initStyleOption(option)

    # 绘制控件框架
    painter.drawComplexControl(QStyle.CC_ComboBox, option)

    # 手动居中文本
    text_rect = self.style().subControlRect(
    QStyle.CC_ComboBox, option, QStyle.SC_ComboBoxEditField)
    text_rect.adjust(25, 0, 0, 0)
    painter.drawText(text_rect, Qt.AlignCenter, self.currentText())
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2353 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 02:04 · PVG 10:04 · LAX 19:04 · JFK 22:04
    ♥ Do have faith in what you're doing.