gpt4 book ai didi

c++ - 通过 C++ 在 qml 中交换 QString

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:57:32 25 4
gpt4 key购买 nike

此示例应该从 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: Result of expression 'data.setTeamName' [undefined] is not a function。Main.qml:51: 错误:无法将 [undefined] 分配给 QString

最佳答案

teamNamedata 的属性,因此只需使用赋值运算符,如 data.teamName = 'some text';

也许你应该将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com