此示例应该从TextInput读取字符串,并在单击鼠标时将其显示在另一个Rectangle中。但是,事实并非如此。为什么?

//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QDeclarativeView>
#include <QDeclarativeContext>
#include <QObject>
#include <QString>

class MainWindow : public QDeclarativeView
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
};

class Data : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString teamName READ getTeamName WRITE setTeamName NOTIFY nameChanged)

public:
    Data(QObject *parent = 0);
    ~Data();

public:
    QString getTeamName();
    void setTeamName(QString &);

signals:
    void nameChanged();

private:
    QString n_teamName;
};

#endif // MAINWINDOW_H

//mainwindow.cpp
#include "mainwindow.h"
#include <QDeclarativeView>
#include <QDeclarativeContext>
#include <QString>
#include <QObject>

MainWindow::MainWindow(QWidget *parent)
    : QDeclarativeView(parent)
{

}

MainWindow::~MainWindow()
{

}

Data::Data(QObject *parent) : QObject(parent)
{
    //n_teamName = "Ahoj";
}

Data::~Data(){

}

QString Data::getTeamName(){
    return n_teamName;
}

void Data::setTeamName(QString &newName){
    if(newName != n_teamName){
        n_teamName = newName;
        emit nameChanged();
    }
}

//main.cpp
#include "mainwindow.h"
#include <qdeclarative.h>
#include <QApplication>
#include <QDeclarativeView>
#include <QDeclarativeContext>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    Data d;
    qmlRegisterType<Data>("NData", 1, 0, "Data");
    w.rootContext()->setContextProperty("data", &d);
    w.setSource(QUrl::fromLocalFile("../klik/Main.qml"));

    w.show();

    return a.exec();
}

//main.qml
// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
import QtQuick 1.1
import NData 1.0
Rectangle {
    id: root
    width: 600
    height: 400
    Rectangle{
        id: text
    ...
        TextInput{
            anchors.fill: text
            anchors.margins: 3
            focus: true
         }
    }
    Rectangle{
    ...
        Text{
            id: copyText
            anchors.centerIn: copy
            text: data.setTeamName()
        }
    }
    Rectangle{
        id: klik
        ...
        MouseArea{
        ...
            onClicked: {
                copyText.text = data.teamName
            }
        }
    }
}

它排除了错误:TypeError:表达式'data.setTeamName'[未定义]的结果不是函数。
Main.qml:51:错误:无法将[undefined]分配给QString

最佳答案

teamNamedata的属性,因此只需使用data.teamName = 'some text';这样的assign运算符

可能您应该将id字段添加到TextInput中,例如

TextInput{
    id: textInput
    anchors.fill: text
    anchors.margins: 3
    focus: true
}

并更改onClicked,所以
MouseArea{
   ...
    onClicked: {
        data.teamName = textInput.text
        copyText.text = data.teamName // copyText.text = textInput.text is fine too
    }
}

关于c++ - 通过C++在QML中进行QString交换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16111155/

10-11 16:24