Qt 5- QTextEdit恢复默认字体

Qt 5- QTextEdit reverts to default font

本文关键字:默认 字体 恢复 QTextEdit Qt      更新时间:2023-10-16

我正在使用QT库编写文本编辑器。我为我的主编辑器小部件子类化QTextEdit

下面是我的代码:

editorwidget.hpp

#ifndef EDITORWIDGET_H_INCLUDED
#define EDITORWIDGET_H_INCLUDED
#include <QTextEdit>
#include <QFile>
class EditorWidget : public QTextEdit
{
    Q_OBJECT
    public:
    EditorWidget(const QString& filename, QWidget* parent = 0);
    ~EditorWidget();
    public slots:
    void saveRequested();
    //...
    private:
    QFile* editorFile;
};
#endif

editorwidget.cpp

#include "editorwidget.hpp"
EditorWidget::EditorWidget(const QString& filename, QWidget* parent)
    : QTextEdit(parent)
{
    this->setFontPointSize(getFontSize()); // this is in another file
    this->setFontFamily(getFont()); // also in another file
    // those two functions get the font and font size from the user's settings
    this->editorFile = new QFile(filename);
}
EditorWidget::~EditorWidget()
{
    if(this->editorFile->isOpen()) this->editorFile->close():
    delete editorFile;
}
...

创建EditorWidget时,字体会正确显示。但是,当我输入一些文本,然后删除它时,小部件恢复到默认字体。

我不明白发生了什么事;我搜索了Google和Stack Overflow,但一无所获。任何帮助都将非常感激。谢谢!

这个线程可能会有所帮助。setFont...()函数设置编辑游标后面的格式,但默认格式不受其影响。QT文档也解释了这种情况。

"…当前的样式用于呈现所有标准Qt小部件的内容,可以自由选择使用小部件字体,或者在某些情况下忽略它(部分地或完全地)。特别是,某些样式,如GTK样式、Mac样式、Windows XP和Vista样式,对小部件字体进行了特殊修改,以匹配平台的本机外观和感觉。因此,为小部件的字体分配属性并不能保证改变小部件的外观。"

在你的情况下,你可以尝试setStyleSheet()代替。