【问题标题】:Can I implement a random font selection?我可以实现随机字体选择吗?
【发布时间】:2019-10-29 19:14:21
【问题描述】:

我有一个在标签上显示一些消息的程序(使用 QtDesigner):

from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow


class MyWidget(QMainWindow):
    def __init__(self):
        super().__init__()
        uic.loadUi('main1.ui', self)
        self.run()

    def run(self):
        self.label.setText('Message')


app = QApplication(sys.argv)
ex = MyWidget()
ex.show()
sys.exit(app.exec_())

此消息以 QtDesigner 中所选字体显示,我的标签的 StyleSheet:

问题是:我该怎么做才能让这个字体被随机选择?是否可以? (完美案例:每次我运行我的程序时,它都会以随机选择的字体显示我的消息)

【问题讨论】:

    标签: python pyqt pyqt5 qt-designer


    【解决方案1】:

    您可以通过QFontDatabasefamilies()方法获取所有可用的family,随机选择一个,构建一个QFont并设置在QLabel中:

    import random
    import sys
    
    from PyQt5 import uic
    from PyQt5.QtGui import QFont, QFontDatabase
    from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow
    
    
    class MyWidget(QMainWindow):
        def __init__(self):
            super().__init__()
            uic.loadUi("main1.ui", self)
    
            db = QFontDatabase()
            family = random.choice(db.families())
            print(family)
            font = db.font(family, "", 72)
            # also random style:
            # style = random.choice(db.styles(family))
            # font = db.font(family, style, 72)
            self.label.setFont(font)
    
            self.run()
    
        def run(self):
            self.label.setText("Message")
    
    
    if __name__ == "__main__":
    
        app = QApplication(sys.argv)
        ex = MyWidget()
        ex.show()
        sys.exit(app.exec_())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多