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);
    }
}

效果:

相关推荐
chuan.bai1 小时前
Java RAG 实战(第 11 篇):RAG 知识工作台网页
java·开发语言·人工智能
离陌在学C#3 小时前
C# 事件(Event)详解:从概念到实战
开发语言·c#
Terra.K4 小时前
Java异常学习[特殊字符]
java·开发语言·学习
葡萄城技术团队5 小时前
InfluxDB 2\.x 深度解析:核心架构、Flux 函数与制造业落地指南(三)
java·开发语言·架构
counting money5 小时前
Java IO流详解:从InputStream到文件操作实战
java·开发语言·python
wuyk5556 小时前
98.C语言易混难点:字符数组与字符串指针的底层差异
c语言·开发语言·c++·stm32·嵌入式硬件·算法
峥无6 小时前
从0到1手撕红黑树:封装实现 my_map 与 my_set(SGI-STL 源码级深度解析)
开发语言·c++·笔记·算法·stl
波特率1152006 小时前
C++新特性---属性说明符与标准属性
开发语言·c++
程序员小八7776 小时前
上海百度B端java后端日常实习一面
java·开发语言
wp123_16 小时前
IPX8 防水 Type‑C连接器:安费诺 124018792112A 与 TONEVEE TY48087‑24A 技术梳理
c语言·开发语言