QComboBox设置字体样式

Love The Way You Lie 2022-05-10 05:14 1327阅读 0赞

一、我们希望将系统的字体添加到下拉列表中,并且在工具栏中显示,效果如下图所示:

70

二、单纯的用QComboBox是不能获取字体样式的,QComboBox仅仅是一个下拉列表,并不能获取系统字体,Qt专门提供了一个类QFontComboBox来获取下拉式的系统字体;

参考Qt助手查看QFontComboBox类的第一句是The QFontComboBox widget is a combobox that lets the user select a font family.另外需要配合使用的就是QTextCharFormat类,因为它提供了setFontFamily()函数来设置系统字体;

三、将下拉列表添加到工具栏中必须用代码,不能在ui界面拖动添加。类似的还有QSpinBox、QLabel

四、添加头文件

  1. #include <QSpinBox>
  2. #include <QFontComboBox>
  3. #include <QLabel>
  4. #include <QTextCharFormat>

五、定义两个指针,添加槽函数

  1. private:
  2. Ui::MainWindow *ui;
  3. QSpinBox *spinBox;
  4. QFontComboBox *comboBox;
  5. private slots:
  6. void spinBoxSlot(int FontSize);
  7. void comboBoxSlot(const QString &arg1);

六、cpp文件

  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3. MainWindow::MainWindow(QWidget *parent) :
  4. QMainWindow(parent),
  5. ui(new Ui::MainWindow)
  6. {
  7. ui->setupUi(this);
  8. ui->mainToolBar->addWidget(new QLabel("字体大小"));
  9. spinBox = new QSpinBox;
  10. spinBox->setValue(ui->textEdit->font().pointSize());
  11. ui->mainToolBar->addWidget(spinBox);
  12. ui->mainToolBar->addWidget(new QLabel("字体"));
  13. comboBox = new QFontComboBox;
  14. comboBox->setMinimumWidth(150);
  15. ui->mainToolBar->addWidget(comboBox);
  16. connect(spinBox,SIGNAL(valueChanged(int)),this,SLOT(spinBoxSlot(int)));
  17. connect(comboBox,SIGNAL(currentIndexChanged(QString)),this,SLOT(comboBoxSlot(const QString &)));
  18. }
  19. MainWindow::~MainWindow()
  20. {
  21. delete ui;
  22. }
  23. void MainWindow::spinBoxSlot(int FontSize)
  24. {
  25. QTextCharFormat fmt;
  26. fmt.setFontPointSize(FontSize);
  27. ui->textEdit->mergeCurrentCharFormat(fmt);
  28. }
  29. void MainWindow::comboBoxSlot(const QString &arg1)
  30. {
  31. QTextCharFormat fmt;
  32. fmt.setFontFamily(arg1);
  33. ui->textEdit->mergeCurrentCharFormat(fmt);
  34. }

发表评论

表情:
评论列表 (有 0 条评论,1327人围观)

还没有评论,来说两句吧...

相关阅读