V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · 2213 views
    This topic created in 435 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   ·   Solana   ·   2309 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 15:52 · PVG 23:52 · LAX 08:52 · JFK 11:52
    ♥ Do have faith in what you're doing.