代码之家  ›  专栏  ›  技术社区  ›  Richard Smith

字体菜单PyQt5文本编辑器

  •  1
  • Richard Smith  · 技术社区  · 8 年前

    问题是:

    我试图找到一种方法,将字体样式添加到由PyQt5文本编辑器程序的用户编写的文本中。我不想手动将每种字体编码到某种菜单中,我想知道是否有一种内置方式可以让用户像这样为文本选择字体样式(记事本字体选择器):

    Notepad fonts

    class App(QMainWindow):
        def __init__(self):
            super().__init__()
            self.title = 'Text Editor'
            self.left = 10
            self.top = 10
            self.width = 1080
            self.height = 920
    
            self.widget = QWidget(self)
            self.lbl    = QLabel(self)
    
            self.text = QTextEdit(self.widget)
            self.widget.setLayout(QVBoxLayout())
            self.widget.layout().addWidget(self.text)
            self.setCentralWidget(self.widget)
            self.initUI()
    
    
    
       def initUI(self):
            self.setWindowTitle(self.title)
            self.setGeometry(self.left, self.top, self.width, self.height)
    
            toolBar = self.menuBar()
            fileMenu = toolBar.addMenu('File')
            editMenu = toolBar.addMenu('Edit')
            toolsMenu = toolBar.addMenu('Tools')
            helpMenu = toolBar.addMenu('Help')
    
            fontButton = QAction('Configure Editor', self)
            fontButton.setShortcut('Ctrl+E')
            fontButton.triggered.connect(lambda: self.font_set)
            toolsMenu.addAction(fontButton)
    
            self.show()
    
       def font_set(self):
            print("Display Fonts")
    
    
    if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   eyllanesc    8 年前

    Qt有一个名为 QFontDialog ,这非常适合这种情况,在下面的部分中,我展示了它的使用示例:

    def font_set(self):
        font, ok = QFontDialog.getFont(self.text.font(), self)
        if ok:
            #QApplication.setFont(font)
            self.text.setFont(font)
            print("Display Fonts", font)
    

    您必须更改以下声明:

    fontButton.triggered.connect(lambda: self.font_set)
    

    收件人:

    fontButton.triggered.connect(self.font_set)
    

    enter image description here