2017-09-27 74 views
0

問題:字體菜單PyQt5文本編輯器

我試圖找到添加字體樣式的文本的方式,如寫我的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_()) 

回答

2

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