【发布时间】:2021-02-05 09:05:27
【问题描述】:
我正在使用 Qt (https://doc.qt.io/qt-5/qtquickcontrols1-texteditor-example.html) 提供的示例中的 TextEditor。这是完整的代码https://code.qt.io/cgit/qt/qtquickcontrols.git/tree/examples/quickcontrols/controls/texteditor?h=5.15
我创建了一个自定义方法 void DocumentHandler::setBackgroundColor(const QColor &color) 来更改整个 HTML 文档的背景颜色。
我的问题是每当我调用一个方法来使用setDefaultStyleSheet 更改QTextDocument 的背景颜色时,它只执行一次。即,我的文档背景只更改一次。对于接下来的调用,我可以看到 qDebug 打印正确,但 setDefaultStyleSheet 不起作用。但是,所有内容都适用于普通文本,但不适用于 m_doc->toHtml()。
我该如何解决这个问题?
如果我更改 m_doc->setHtml("some random text"),它会按要求工作
...
QColor DocumentHandler::backgroundColor() const
{
return m_backgroundColor;
}
void DocumentHandler::setBackgroundColor(const QColor &color)
{
m_backgroundColor = color.name(); // QColor variable
m_doc->setDefaultStyleSheet("body{background-color: '"+ color.name() +"'}"); // m_doc is QTextDocument *
m_doc->setHtml(m_doc->toHtml());
qDebug() << "BACKGROUND COLOR CHANGED" << color.name() ;
emit backgroundColorChanged();
}
在 QML 中,我是这样称呼的
...
DocumentHandlerModel {
id: document
target: textArea
cursorPosition: textArea.cursorPosition
selectionStart: textArea.selectionStart
selectionEnd: textArea.selectionEnd
backgroundColor: colorDialog2.color
onFontFamilyChanged: {
var index = Qt.fontFamilies().indexOf(document.fontFamily)
if (index === -1) {
fontFamilyComboBox.currentIndex = 0
fontFamilyComboBox.special = true
} else {
fontFamilyComboBox.currentIndex = index
fontFamilyComboBox.special = false
}
}
onError: {
errorDialog.text = message
errorDialog.visible = true
}
}
【问题讨论】:
-
这是否回答了您的问题:stackoverflow.com/a/26249813/5366641?
-
@scopchanov,即
QLabel。我找不到QTextDocument的任何此类方法。我认为你是对的。我需要以某种方式刷新它。但不知道具体方法 -
确实如此。答案是小部件。
QTextDocument工作方式不同。我现在的事业已经。给我一些时间来寻找解决方案,我会给你写一个答案。