字型對話框(QFontDialog)

Qt裡用QFontDialog提供字型樣式,讓使用者選擇字型,供程式後續使用。範例裡當我們按下開啟對話框按鍵,之後會跳出字型對話框,選擇我們想要的字型,標籤上的字會因為選擇的字型而改變。


dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QLabel>
#include <QVBoxLayout>
#include <QPushButton>

class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = 0);
private:
    QPushButton *fontBtn;
    QLabel *fontLabel;
    QVBoxLayout *mainLayout;
private slots:
    void showFont();
};

#endif 

dialog.cpp

#include "dialog.h"
#include<QFontDialog>

Dialog::Dialog(QWidget *parent) : 
    QDialog(parent)
{
    setWindowTitle(QStringLiteral("字型對話框"));
    fontBtn = new QPushButton;
    fontBtn->setText(QStringLiteral("開啟字型對話框"));
    fontLabel = new QLabel;
    fontLabel->setText(tr("哈囉! Qt"));
    fontLabel->setAlignment(Qt::AlignCenter);   //label文字置中
    mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(fontBtn);
    mainLayout->addWidget(fontLabel);
    connect(fontBtn,SIGNAL(clicked()),this,SLOT(showFont()));
}

void Dialog::showFont()
{
    bool ok;
    QFont f = QFontDialog::getFont(&ok);
    if (ok){
        fontLabel->setFont(f);
    }
}

main.cpp

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.resize(100,70);
    w.show();

    return a.exec();
}

QFontDialog

QFontDialog