【发布时间】:2014-01-29 13:03:57
【问题描述】:
我正在尝试设置我的程序以从 QML 的输入字段中获取数据,然后将该数据传递给 C++,这将用于进行属性更改。例如,如果用户在输入字段中键入红色,则包含输入字段的矩形应变为红色。数据在 C++ 中被接收,但矩形的属性没有改变。
这是我的代码。任何帮助表示赞赏。
main.qml
Rectangle{
id: textbox
radius: 15.0
height: 300
width: 300
color: "white"
border.color: "lightblue"
border.width: 5
signal qmlSignal(string msg)
property alias textColor: colorText.color
TextInput
{
id: inputText
anchors.horizontalCenter: textbox.horizontalCenter
anchors.verticalCenter: textbox.verticalCenter
anchors.bottomMargin: 25
color : "black"
text : "type something..."
font.pointSize: 20
maximumLength: 17
inputMethodHints: Qt.ImhNoPredictiveText
selectByMouse: true
onAccepted: { inputText.focus = false;
Qt.inputMethod.hide();
textbox.qmlSignal(inputText.text);
console.log(colorText.color) }
}
}
main.cpp
#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
#include <QtQuick>
#include <QObject>
#include <myclass.h>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/Test3/main.qml"));
QObject *item = viewer.rootObject();
MyClass test;
QObject::connect(item, SIGNAL(qmlSignal(QString)), &test, SLOT(cppSlot(QString)));
viewer.showExpanded();
return app.exec();
}
myclass.h
#include<QObject>
#include<QDebug>
#include<QtQuick>
#include"qtquick2applicationviewer.h"
class MyClass: public QObject
{
Q_OBJECT
public:
MyClass();
public slots:
void cppSlot(const QString &msg)
{
qDebug() << "Called the C++ slot with message:" << msg;
QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/Test3/main.qml"));
QObject *item = viewer.rootObject();
item->setProperty("color", "red");
}
};
【问题讨论】:
标签: c++ qt properties qml