如何更改文本的笔触粗细?

时间:2020-04-02 06:47:48

标签: python qt pyqt5 qtstylesheets

我想更改文本的粗细。

在CSS中有一个属性

-webkit-text-stroke-width

PyQt5中是否有类似物

将字体更改为较细的字体是不可行的,因为我使用的字体不具有粗斜体等。

import sys
from PyQt5.QtWidgets import (QRadioButton, QHBoxLayout, QButtonGroup, 
    QApplication, QGraphicsScene,QGraphicsView, QGraphicsLinearLayout, QGraphicsWidget, QWidget, QLabel)
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtCore import QSize, QPoint,Qt
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPainter


class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.resize(800, 800)
        label = QLabel(self)
        label.setText('<div>&#xe202;</div>')

        font_id = QFontDatabase.addApplicationFont(url)
        if font_id == -1:
            print('not fond')



        font = QFont("my-font",18)



        label.setStyleSheet('''font-size: 80pt; font-family: my-font;''')



if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

您可以尝试使用font-weight属性,值100-900具有不同的厚度。 QFont.setWeight()有一个等效的方法。

class Template(QWidget):

    def __init__(self):
        super().__init__()
        grid = QGridLayout(self)
        grid.addWidget(QLabel('Hello World'), 0, 0, Qt.AlignHCenter)
        for i in range(1, 10):
            lbl = QLabel(f'({i * 100}) Hello World')
            lbl.setStyleSheet(f'font-weight: {i * 100}')
            grid.addWidget(lbl, i, 0)
        self.setStyleSheet('''
        QLabel {
            font-size: 24pt;
            font-family: Helvetica Neue;
        }''')

它看起来像这样:

enter image description here

尽管这不适用于所有字体。您可以选择子类QLabel和重新实现paintEvent以用窗口颜色绘制文本的轮廓。

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class ThinLabel(QLabel):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def paintEvent(self, event):
        qp = QPainter(self)
        qp.setRenderHint(QPainter.Antialiasing)
        path = QPainterPath()
        path.addText(event.rect().bottomLeft(), self.font(), self.text())
        qp.setPen(QPen(self.palette().color(QPalette.Window), 2))
        qp.setBrush(self.palette().text())
        qp.drawPath(path)


class Template(QWidget):

    def __init__(self):
        super().__init__()
        grid = QGridLayout(self)
        grid.addWidget(QLabel('Hello World'), 0, 0)
        grid.addWidget(ThinLabel('Hello World'), 1, 0)
        self.setStyleSheet('''
        QLabel {
            font-size: 80pt;
            font-family: Helvetica Neue;
        }''')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    gui = Template()
    gui.show()
    sys.exit(app.exec_())

enter image description here

相关问题