import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton
from PyQt5.QtGui import QFont, QFontDatabase
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self.button = None
self.label = None
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('PyQt5 Example')
self.label = QLabel(self)
self.label.setGeometry(100, 50, 200, 30)
self.label.setText("显示")
font_id = QFontDatabase.addApplicationFont(r'字体\a.ttf') # 替换自己的字体,路径需更换
font_families = QFontDatabase.applicationFontFamilies(font_id)
font_family = font_families[0] if font_families else '黑体'
self.label.setFont(QFont(font_family, 12)) # 设置字体为a.ttf
self.button = QPushButton('Change Text', self)
self.button.setGeometry(100, 100, 100, 30)
self.button.clicked.connect(self.changeText)
def changeText(self):
self.label.setText("什么字体")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
set_font_recursive是为了遍历搜索部件;
注意:不能在qss里添加字体,否则那个部件更改无效。
无效的情况还有很多种,需要仔细看qss了
def set_font_recursive(widget, font):
# 设置当前部件的字体
widget.setFont(font)
# 如果当前部件是容器部件(如窗口、布局等),则递归设置其子部件的字体
if isinstance(widget, QWidget):
for child_widget in widget.findChildren(QWidget):
set_font_recursive(child_widget, font)
class Stats(QMainWindow, Ui_Form):
def __init__(self):
super().__init__()
self.setupUi(self)
font_id = QFontDatabase.addApplicationFont(r'字体\c.ttf') # 替换自己的字体,路径需更换
font_families = QFontDatabase.applicationFontFamilies(font_id)
font_family = font_families[0] if font_families else '黑体'
font = QFont(font_family, 12)
font.setBold(True) # 添加加粗效果
set_font_recursive(self, font) # 递归更改字体
self.label.setFont(QFont(font_family, 24)) # 特殊定制,大小可变
self.label_readme1.setFont(QFont(font_family, 14))
self.label_readme2.setFont(QFont(font_family, 14))