QML 与 QT之间的传值问题

tony2278 2017-11-20 10:16:19



//MyClass.h
#include <QObject>
class MyClass : public QObject
{
Q_OBJECT
Q_INVOKABLE QString GetPath1();
Q_INVOKABLE QString GetPath2();

public:
MyClass();

private:
QString m_Pathdir;
QString m_Filename1;
};


//main.cpp
#include "myclass.h"
int main(int argc, char* argv[])
{
QGuiApplication app(argc, argv);

qmlRegisterType<MyClass>("Qt.MyClass", 1, 0, "MyClass");
QQmlApplicationEngine engine;
engine.load(QStringLiteral("path.qml"));

return app.exec();
}


//path.qml
import Qt.MyClass 1.0
Window
{
id: root
visible: true

MyClass
{
id: myClass
}

property string pathdir: myClass.GetPath1()
property string fileName2: myClass.GetPath2()
}



编译没有问题,但是在运行的时候报错:
path.qml: TypeError: Property 'GetPath1' of object MyClass(0x55c01ca599e0) is not a function
path.qml: TypeError: Property 'GetPath2' of object MyClass(0x55c01ca599e0) is not a function


请问应该怎样解决?谢谢!

另外:使用 import Qt.MyClass 1.0 这种形式,应该在哪里 new 一个 class MyClass 实例出来呢?




...全文
409 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
抱歉,不了解,关注。
tony2278 2017-11-22
  • 打赏
  • 举报
回复
Qt 5.9 Qt Quick C++ Classes QQuickView
tony2278 2017-11-20
  • 打赏
  • 举报
回复
现在的新问题是: 成员变量 m_Pathdir 和 m_Filename1, 怎样才能在 main.cpp 里面的

// initialize MyClass  m_Pathdir   BY HOW?
// initialize MyClass  m_Filename1  BY HOW?

qmlRegisterType<MyClass>("Qt.MyClass", 1, 0, "MyClass");
    QQmlApplicationEngine engine;
    engine.load(QStringLiteral("path.qml"));
逻辑之前被赋值?

#include "myclass.h"

MyClass::MyClass()
{
    m_Pathdir = "file:///home/tt1/workspace/prd3/";  // not initialize here ,  how can I initialize it in main()?
    m_Filename1 = "20170504102730_0.png";    //  not initialize here , how can I initialize it in main()?
}

QString MyClass::GetPath1()
{
    return m_Pathdir;
}

QString MyClass::GetPath2()
{
    return m_Filename1;
}

//......
tony2278 2017-11-20
  • 打赏
  • 举报
回复
改之前是以下的版本(unworking version):


//MyClass.h
#include <QObject>
class MyClass : public QObject
{
    Q_OBJECT
    Q_INVOKABLE QString GetPath1();
    Q_INVOKABLE QString GetPath2();
 
public:
    MyClass();
 
private:
    QString m_Pathdir;
    QString m_Filename1;
};

tony2278 2017-11-20
  • 打赏
  • 举报
回复
我把它改成以下这种方式,好像 Working 了!


class MyClass : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString mypath READ GetPath1 WRITE setMember3 )

public:
    MyClass();
    Q_INVOKABLE QString GetPath1();
    Q_INVOKABLE QString GetPath2();
    Q_INVOKABLE void setMember3( const QString& mem3 ); //This is Empty function

public slots:
    void cppSlot(int number);

private:
    QString m_Pathdir;
    QString m_Filename1;
};

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧