Pyqt5系列(四)-基本界面组件之Dialog(2)

在大部分的操作系统中,为了更好的实现人机交互,windows以及linux中均为提供一系列的对话框来完成特定场景下的功能,诸如字体大小选择,字体颜色选择等等。PyQt5中定义了一些列的标准对话框的类,让使用者能够方便和快捷的通过各个类完成字体大小、颜色,以及文件的选择.

QFontDialog

#-*- coding:utf-8 -*-
'''
QFontDialog
'''
__author__ = 'Tony Zhu'

from PyQt5.QtWidgets import QApplication, QDialog,QWidget, QFontDialog, QPushButton, QLineEdit, QGridLayout
import sys
import os


class FontDialog(QDialog):
    def __init__(self):
        super(FontDialog,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QFontDialog")
        self.setGeometry(400,400,300,260)

        self.fontButton = QPushButton("字体选择对话框")
        self.fontLineEdit = QLineEdit("Hello Python")
        self.fontButton.clicked.connect(self.openFont)

        self.mainLayout = QGridLayout()
        self.mainLayout.addWidget(self.fontButton,0,0)
        self.mainLayout.addWidget(self.fontLineEdit,0,1)

        self.setLayout(self.mainLayout)

    def openFont(self):
         font,ok=QFontDialog.getFont()  
         if ok:
            self.fontLineEdit.setFont(font) 


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

运行之后的效果:
这里写图片描述
这里写图片描述
控件说明:

控件类型 控件名称 作用
QPushButton fontButton 打开字体选择对话框
QLineEdit fontLineEdit 显示设定字体类型的效果

示例说明:
通过字体选择对话框选择对应的字体,并且选择的字体效果设定在QLineEdit中显示的文本上。
代码分析:
L21~23:

        self.fontButton = QPushButton("字体选择对话框")
        self.fontLineEdit = QLineEdit("Hello Python")
        self.fontButton.clicked.connect(self.openFont)

实例化fontButton 和fontLineEdit 对象,并将fontButton的clicked信号和槽函数openFont()绑定在一起。

L25~27:

self.mainLayout = QGridLayout()
        self.mainLayout.addWidget(self.fontButton,0,0)
        self.mainLayout.addWidget(self.fontLineEdit,0,1)

实例化网格布局,并将fontButton和fontLineEdit按照对应的位置添加到网格布局中。

L31~34:

    def openFont(self):
         font,ok=QFontDialog.getFont()  
         if ok:
            self.fontLineEdit.setFont(font) 

自定义的槽函数,选择所需的字体,并将字体的效果设定到fontLineEdit中。getFont()方法返回的为元组类型,同时返回选择的字体和函数执行的状态。

 |  getFont(...)
 |      QFontDialog.getFont(QFont, QWidget parent=None, str caption=QString(), QFontDialog.FontDialogOptions options=0) -> (QFont, bool)
 |      QFontDialog.getFont(QWidget parent=None) -> (QFont, bool)

getFont()方法有两个重载的实现,对应如上所需的参数不同,在上面的示例中,我们采用的是第二个实现。

QFontDialog.getFont(QFont, QWidget parent=None, str caption=QString(), QFontDialog.FontDialogOptions options=0) -> (QFont, bool)

第1个参数parent,用于指定父组件;

第2个参数caption,是QFileDialog对话框的标题;

第3个参数options,是对话框的一些参数设定,它的取值是 QFontDialog.FontDialogOptions ,每个选项可以使用 | 运算组合起来。

返回值为(QFont,bool),即返回值类型为tuple(元组)。

--------------------- 本文来自 追逐阳光的风 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/zhulove86/article/details/52513837?utm_source=copy

猜你喜欢

转载自blog.csdn.net/IAlexanderI/article/details/82938845