【问题标题】:How to set the text in the QComboBox to align to the center without making it editable in PyQt如何将 QComboBox 中的文本设置为与中心对齐而不使其在 PyQt 中可编辑
【发布时间】:2017-12-15 13:38:21
【问题描述】:

我发现这样做

self.combo.setEditable(True)
self.combo.lineEdit().setAlignment(QtCore.Qt.AlignCenter)

将使组合框中的文本居中对齐。但是一旦我这样做了,我应用到组合框的样式就不起作用了,其中显示的文本将是默认的纯文本。另外我不想让它可编辑,我不喜欢当我们将它设置为可编辑时出现的 GUI 效果。

是否有一种简单的方法可以使文本居中对齐,同时保留与以前相同的 GUI 效果(例如样式和单击时的行为)?

【问题讨论】:

  • 我什至尝试将组合框设置为只读。但这无济于事
  • 没有办法,只能重新实现paintEvent()方法
  • 如果您提供一个小代码 sn-p 以使用该方法执行粗体文本之类的操作,这将对您非常有帮助...无论如何我会查看文档

标签: python combobox pyqt alignment center


【解决方案1】:

您可以通过这种方式自己重新实现组合框绘图例程(我正在处理的项目中的 sn-p):

class CustomComboBox(QtGui.QComboBox):
    ...

    def paintEvent(self, evt):
        painter = QtGui.QStylePainter(self)
        painter.setPen(self.palette().color(QtGui.QPalette.Text))
        option = QtGui.QStyleOptionComboBox()
        self.initStyleOption(option)
        painter.drawComplexControl(QtGui.QStyle.CC_ComboBox, option)
        textRect = QtGui.qApp.style().subControlRect(QtGui.QStyle.CC_ComboBox, option, QtGui.QStyle.SC_ComboBoxEditField, self)
        painter.drawItemText(
            textRect.adjusted(*((2, 2, -1, 0) if self.isShown else (1, 0, -1, 0))),
            QtGui.qApp.style().visualAlignment(self.layoutDirection(), QtCore.Qt.AlignLeft),
            self.palette(), self.isEnabled(),
            self.fontMetrics().elidedText(self.currentText(), QtCore.Qt.ElideRight, textRect.width())
        )

   ...

painter.drawItemText 调用是绘制文本的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2013-07-13
    • 2017-01-07
    • 2021-01-24
    • 2019-06-01
    相关资源
    最近更新 更多