QT_QFontDialog类字体对话框

文章目录

QT_QFontDialog类字体对话框

QFontDialog 是 Qt 框架中用于让用户选择字体(包括字体族、大小、样式等)的标准对话框组件,继承自 QDialog,属于 Qt Widgets 模块。

功能与使用方式

静态方法快速调用

最常用的是 QFontDialog::getFont(),它会弹出一个模态对话框,用户选择后返回一个 QFont 对象和一个布尔值(表示是否点击"确定")。

实例化自定义对话框

也可以创建 QFontDialog 对象,通过 exec() 或 open() 显示,并连接 currentFontChanged 信号实现实时预览。

支持选项配置

可通过 FontDialogOption 枚举控制对话框行为,例如:

  • DontUseNativeDialog:强制使用 Qt 自绘界面而非系统原生对话框。
  • NoButtons:隐藏"确定"和"取消"按钮,适合嵌入自定义界面。
  • ScalableFonts:仅显示可缩放字体。

代码示例

cpp 复制代码
#include <QFontDialog>
#include <QFont>

bool ok;
QFont font = QFontDialog::getFont(&ok, QFont("Arial", 12), this, "选择字体");
if (ok) {
    // 用户点击了"确定",font 包含所选字体
    myLabel->setFont(font);
} else {
    // 用户点击了"取消"
}

使用案例

dialog.h

cpp 复制代码
#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QPushButton>
#include <QFontDialog>
#include <QGridLayout>
#include <QLineEdit>

class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = nullptr);
    ~Dialog();
private:
    QGridLayout *glayout;
    QPushButton *fontbutton;
    QLineEdit *fontlineedit;
private slots:
    void displayFontFunc();
};
#endif // DIALOG_H

dialog.cpp

cpp 复制代码
#include "dialog.h"

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
{
    setWindowTitle(u8"字体对话框测试");
    glayout = new QGridLayout(this);

    fontbutton = new QPushButton(u8"调用字体对话框");

    fontlineedit = new QLineEdit;

    fontlineedit->setText(u8"天王盖地虎");

    glayout->addWidget(fontbutton, 0, 0);
    glayout->addWidget(fontlineedit, 0, 1);
    connect(fontbutton, SIGNAL(clicked()), this, SLOT(displayFontFunc()));

}
Dialog::~Dialog()
{
}

void Dialog::displayFontFunc(){
    bool isbool;
    QFont font = QFontDialog::getFont(&isbool);

    if (isbool) {
        fontlineedit->setFont(font);
    }
}

效果:

相关推荐
可涵不会debug9 小时前
C++ std::bind 实战教程:线程池、回调场景全覆盖
linux·开发语言·c++
不正经的码狗9 小时前
Java 开发环境搭建与 Eclipse 使用速通教程
java·开发语言·eclipse
阿钱真强道9 小时前
24 嵌入式操作系统 | 项目启动与环境准备(PyQt5 / Flask 两个“最小可跑“)
开发语言·qt·flask·架构设计·协议契约
霸道流氓气质9 小时前
AI模型幻觉检测与抑制完全指南:从规则引擎到RAG对比的Java生产级实战
java·开发语言·人工智能
前端 贾公子9 小时前
LangChain核心组件 == 提示词(Prompts)
开发语言·c#
niucloud-admin9 小时前
JAVA V6 多商户商城 开发文档——手机端前端
java·开发语言·前端
茉莉玫瑰花茶9 小时前
GO [ 并发 ]
开发语言·后端·golang
霸道流氓气质9 小时前
Dify 可视化 LLM 应用开发平台完全指南:从Workflow编排到Java生产级集成实战
java·开发语言
2601_9622186110 小时前
深入理解C++中的thread_local线程局部变量的应用
开发语言·c++
外收内放10 小时前
Python基础语法练习题(31-33)
开发语言·python