我的QML文件中有一个TextEdit,我有一个QSyntaxHighlighter C ++类。我想在C ++类中指定突出显示逻辑并将其应用于TextEdit,但我不确定如何在QML对象和C ++类之间建立连接。你还能提供一些示例代码吗?我无法通过Qt文档找到如何实现它。
答案 0 :(得分:4)
您可以使用包含TextEdit::textDocument
实例的QQuickTextDocument
来访问您可以传递给QTextDocument
构造函数的基础QSyntaxHighlighter
。
答案 1 :(得分:0)
如果有人需要更详细的解释。 首先,我在自定义C ++类中创建了一个Q_PROPERTY。
Q_PROPERTY(QQuickTextDocument* mainTextEdit READ mainTextEdit WRITE setMainTextEdit NOTIFY mainTextEditChanged)
然后我将textEdit.textDocument
分配给QML中的Q_PROPERTY。
customClass.mainTextEdit = textEdit.textDocument
然后我在我的QML中调用initHighlighter()
(函数必须是Q_INVOKABLE),它调用我的荧光笔类的构造函数并将其传递给textEdit的文本文档。
void initHighlighter()
{
Highlighter *highlighter;
highlighter = new Highlighter(m_mainTextEdit->textDocument());
}
注意:自定义荧光笔类需要从QSyntaxHighlighter派生。
答案 2 :(得分:0)
示例实施:
HighlightComponent.h
class HighlightComponent : public QObject
{
Q_OBJECT
//@formatter:off
Q_PROPERTY(QString text
READ getText
WRITE setText
NOTIFY textChanged)
//@formatter:on
using inherited = QObject;
public:
explicit HighlightComponent(QObject* parent = nullptr);
static void registerQmlType();
const QString& getText()
{
return _text;
}
void setText(const QString& newText)
{
if (newText != _text)
{
_text = newText;
emit textChanged();
}
}
Q_INVOKABLE void onCompleted();
signals:
void textChanged();
private:
std::unique_ptr<QSyntaxHighlighter> _highlight;
QString _text = "";
};
HighlightComponent.cpp
HighlightComponent::HighlightComponent(QObject* parent)
: inherited(parent)
{
}
void HighlightComponent::onCompleted()
{
auto property = parent()->property("textDocument");
auto textDocument = property.value<QQuickTextDocument*>();
auto document = textDocument->textDocument();
//TODO init here your QSyntaxHighlighter
}
void HighlightComponent::registerQmlType()
{
qmlRegisterType<HighlightComponent>("com.HighlightComponent", 1, 0, "HighlightComponent");
}
main.cpp
int main(int argc, char* argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
HighlightComponent::registerQmlType();
engine.load(QUrl(QStringLiteral("qrc:/view/main.qml")));
return app.exec();
}
QML示例
TextArea {
id: testTextArea
text: testTextArea.text
//inputMethodHints: Qt.ImhNoPredictiveText
onTextChanged: {
testTextArea.text = text
}
HighlightComponent {
id: testTextArea
Component.onCompleted: onCompleted()
}
}
链接:
https://wiki.qt.io/How_to_Bind_a_QML_Property_to_a_C%2B%2B_Function
http://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html
http://wiki.qt.io/Spell-Checking-with-Hunspell
http://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html
http://doc.qt.io/qt-5/qtwidgets-richtext-syntaxhighlighter-example.html