我正在尝试检索在文本字段中键入的用户输入文本值,但QML找不到我的对象,当我键入某些内容时,Qt Creator的应用程序输出上的以下错误文件
引用错误: 未定义 foo
我错过了什么?注意:非常欢迎任何更好的方法。我刚开始学习QML。
代码如下:
主.cpp
int main(int argc, char *argv[])
{
//qRegisterMetaType<NameUserInput>(NAMEOF(NameUserInput));
//qRegisterMetaType<NameUserInput*>(NAMEOF(NameUserInput*));
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
NameUserInput nameUserInput;
QQmlApplicationEngine engine;
engine.rootContext()->setProperty("foo", //&nameUserInput);
QVariant::fromValue(&nameUserInput));
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
NameUserInput.h
class NameUserInput : public QObject
{
Q_OBJECT
public:
explicit NameUserInput(QObject *parent = nullptr);
//NameUserInput(const NameUserInput &other);
NameUserInput(const QString &text);
~NameUserInput() override = default;
Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
QString text() const;
void setText(const QString &text);
signals:
void textChanged(const QString &text);
private:
QString mText;
};
Q_DECLARE_METATYPE(NameUserInput*)
主.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.5
import QtQuick.Controls.Styles 1.4
Window {
visible: true
width: 640
height: 480
title: qsTr("This is my application title!")
ColumnLayout
{
id: col1
spacing: 2
Rectangle
{
width: 100
Layout.preferredWidth: 40
Layout.preferredHeight: 40
Layout.alignment: Qt.AlignLeft
Text {
font.pointSize: 20
id: label1
text: qsTr("Your name:")
}
}
Rectangle
{
width: 320
Layout.preferredWidth: 40
Layout.preferredHeight: 40
Layout.alignment: Qt.AlignLeft
TextField {
placeholderText: "this is the default text"
font.pointSize: 20
//text: "this is my text"
id: textEdit1
onTextChanged: foo.text = text
background: Rectangle {
border.color: "blue"
border.width: 3
radius: 12
}
}
}
Rectangle
{
width: 100
Layout.preferredWidth: 40
Layout.preferredHeight: 40
Layout.alignment: Qt.AlignLeft
Button
{
text: "Hit me!"
onClicked: console.log("user input:" + textEdit1.text)
}
}
}
}
如果要导出QObject,则应使用setContextProperty()
,而不是setProperty()
。也没有必要使用QVariant。
engine.rootContext()->setContextProperty("foo", &nameUserInput);
另一方面,没有必要使用Q_DECLARE_METATYPE,最好将Q_PROPERTY放在私有部分:
#ifndef NAMEUSERINPUT_H
#define NAMEUSERINPUT_H
#include <QObject>
class NameUserInput : public QObject
{
Q_OBJECT
Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
public:
explicit NameUserInput(QObject *parent = nullptr);
NameUserInput(const QString &text);
~NameUserInput() override = default;
QString text() const;
void setText(const QString &text);
signals:
void textChanged(const QString &text);
private:
QString mText;
};
#endif // NAMEUSERINPUT_H