我想用 Python 重写 Qt/C++ 应用程序。 其中散列一个 QML_ELEMENT 类,该类使用 Qt/Property 将 QQuickTextDocument* 从 QML 传递到 CPP。 Qt/C++ 运行良好。
Python版本出现以下错误;显然,Python版本类不识别指针类型?因为 QQuickTextDocument 不是有效的 QML VALUE TYPE?
/main.qml:15:9: Unable to assign QQuickTextDocument to [unknown property type]
这是 C++ 类声明。
class Createable01 : public QObject
{
Q_OBJECT
QML_ELEMENT
public:
explicit Createable01(QObject *parent = nullptr);
signals:
void textDocumentChanged();
public:
Q_INVOKABLE void colorize(QQuickTextDocument *doc);
QQuickTextDocument *m_textDocument;
QQuickTextDocument *textDocument() const;
void setTextDocument(QQuickTextDocument *newTextDocument);
private:
Q_PROPERTY(QQuickTextDocument *doc READ textDocument WRITE setTextDocument NOTIFY
textDocumentChanged FINAL)
};
我尝试用 Python 编写类,如下所示:
class Creatable(QObject):
name_changed = Signal()
textDocument: QQuickTextDocument
def __init__(self, ):
QObject.__init__(self)
def get_textDocument(self):
return self.textDocument
def set_textDocument(self, newTextDocument):
self.textDocument = newTextDocument
doc = Property(QQuickTextDocument, get_textDocument, set_textDocument)
使用相同的 QML 文件:
Window {
height: 480
title: qsTr("Hello World")
visible: true
width: 640
Creatable {
id: highlighter
doc: textArea.textDocument
}
TextArea {
id: textArea
height: 400
width: 400
anchors {
centerIn: parent
}
}
}
在 PySide6 中,
QSyntaxHighlighter
中的内部 Python 对象是 document: QTextDocument
,但是,在 QML 中,您需要通过 QObject
对其进行编组。所以你可以创建一个自定义的Highlighter: QSyntaxHighlighter
,如下所示:
class Highlighter(QSyntaxHighlighter):
def __init__(self, parent=None):
QSyntaxHighlighter.__init__(self, parent)
def get_textDocument(self):
return self.document
def set_textDocument(self, value):
self.setDocument(QTextDocument(value))
然后您可以将其挂接到 QML 中,如下所示:
Highlighter {
textDocument: textArea.textDocument
}
TextArea {
id: textArea
}