1、概述
QFontDialog 是 Qt 框架中的一个对话框类,用于选择字体。它提供了一个可视化的界面,允许用户选择所需的字体以及相关的属性,如字体样式、大小、粗细等。用户可以通过对话框中的选项进行选择,并实时预览所选字体的效果。QFontDialog 继承自 QDialog,是创建字体选择对话框的标准方式。
2、重要方法
- QFontDialog(QWidget *parent = nullptr): 构造函数,创建一个新的 QFontDialog 对象。parent是可选的父窗口参数。
- static QFont getFont(bool *ok = nullptr, QWidget *parent = nullptr): 静态函数,显示字体对话框并返回用户选择的字体。如果 ok不为nullptr,则当用户点击“确定”时,*ok将被设置为true,否则为false。parent是可选的父窗口参数。
- void setFont(const QFont &font): 设置字体对话框中默认显示的字体。
- void setOption(QFontDialog::FontDialogOption option, bool on = true): 设置字体对话框的选项。option是要设置的选项,on指定该选项是否启用。
3、重要信号
- currentFontChanged(const QFont &font): 当字体对话框中当前选择的字体发生变化时发射此信号。font是新的字体。
- fontSelected(const QFont &font): 当用户在字体对话框中选择字体并点击“确定”时发射此信号。font是用户选择的字体。
#include <QApplication>  
#include <QWidget>  
#include <QLabel>  
#include <QPushButton>  
#include <QVBoxLayout>  
#include <QFontDialog>  
#include <QDebug>  class FontDialogDemo : public QWidget {  Q_OBJECT  public:  FontDialogDemo(QWidget *parent = nullptr) : QWidget(parent) {  QVBoxLayout *layout = new QVBoxLayout(this);  QLabel *label = new QLabel("请选择一个字体:", this);  layout->addWidget(label);  QPushButton *button = new QPushButton("选择字体", this);  layout->addWidget(button);  connect(button, &QPushButton::clicked, this, &FontDialogDemo::onFontButtonClicked);  this->labelToUpdate = new QLabel("Font Dialog 例子", this);  layout->addWidget(this->labelToUpdate);  this->setLayout(layout);  this->setWindowTitle("Font Dialog 例子");  }  private slots:  void onFontButtonClicked() {  bool ok;  QFont font = QFontDialog::getFont(&ok, this);  if (ok) {  this->labelToUpdate->setFont(font);  qDebug() << "选择的字体:" << font.family();  qDebug() << "字体大小:" << font.pointSize();  qDebug() << "字体是否加粗:" << font.bold();  qDebug() << "字体是否是斜体:" << font.italic();  }  }  private:  QLabel *labelToUpdate;  
};  int main(int argc, char *argv[]) {  QApplication app(argc, argv);  FontDialogDemo demo;  demo.show();  return app.exec();  
}  

觉得有帮助的话,打赏一下呗。。
 
           