pyqt5 - 突出显示qpushbutton pyqt中的单个字符
问题描述
我想用红色突出显示单个字符。Fox 在 pyqt5 中的 qpushbutton 中会计中的示例“A”字母。
解决方案
这可以通过自定义样式来实现
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import Qt, QSizeF, QPointF, QRectF
from PyQt5.QtGui import QPalette
class Style(QtWidgets.QProxyStyle):
def __init__(self, style = None):
super().__init__(style)
def drawControl(self, el, opt, p, w):
if el != QtWidgets.QStyle.CE_PushButtonLabel:
return super().drawControl(el,opt,p,w)
text = opt.text
w1 = opt.fontMetrics.horizontalAdvance(text[:1])
w2 = opt.fontMetrics.horizontalAdvance(text[1:])
w = w1 + w2
rect = opt.rect
h = opt.fontMetrics.height()
p1 = rect.topLeft() + QPointF((rect.width() - w) / 2, (rect.height() - h) / 2)
p2 = p1 + QPointF(w1, 0)
rect1 = QRectF(p1, QSizeF(w1, h))
rect2 = QRectF(p2, QSizeF(w2, h))
p.setPen(Qt.red)
p.drawText(rect1, text[:1])
p.setPen(opt.palette.color(QPalette.Text))
p.drawText(rect2, text[1:])
if __name__ == "__main__":
app = QtWidgets.QApplication([])
button = QtWidgets.QPushButton("Accounting")
style = Style(app.style())
button.setStyle(style)
button.show()
app.exec()
推荐阅读
- c++ - 文件模式标志“ios::app”是否用于删除已存在的文件?
- python - 如何从元组列表的第二项中获取最小的项?
- java - 带有时区和毫秒的 LocalDateTime 格式
- python - 无法运行测试脚本。PyCharm Selenium Python 测试
- dart - Dart:将 int 转换为 int Function()
- c# - Azure Batch 和在 Azure 存储中创建容器文件夹
- python - 有没有一种优雅的方法可以将具有不同数量参数的多个函数传递给python中的另一个函数?
- java - 如何检测是否按下退格键?
- docker - 如何终止 dockerfile?
- javascript - 停止加载链接