2014-01-29 115 views
0

我试图设置我的程序从QML中的输入字段获取数据,然后将该数据传递给C++,这将用于更改属性。例如,如果用户在输入字段中键入红色,则包含输入字段的矩形应变为红色。数据正在C++中接收,但矩形上的属性不变。QML/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"); 
} 
}; 

回答

-1

解决你的问题,我相信你会想审查延长教训带绑定的QML。具体请参阅第3章:添加属性绑定,因为它展示了如何使用宏宏Q_PROPERTY在C++对象和QML之间创建绑定。

事实上,我强烈建议您完成Qt Creator的Qt安装附带的所有QML章节。本教程的章节可以通过欢迎页面访问

  1. 选择实例
  2. 在搜索
  3. 六章应列出
输入“