gpt4 book ai didi

c++ - Qt - 无法分配给不存在的属性(自定义 C++ 类)

转载 作者:搜寻专家 更新时间:2023-10-31 02:17:21 24 4
gpt4 key购买 nike

我正在尝试为我的项目制作一个用于 QML 的自定义 TCP 小部件(WebSocket 发送一个 HTTP 请求,它不允许我发送原始 TCP 数据包)。我创建了“TCPSocketConnection”(在 cpp 中命名为 TCPSocketConn)类,并为它提供了一些带有占位符方法的属性,并尝试将其插入到 QML 中。当我尝试使用该类时,出现以下错误

qrc:/qml/qmlwebsocketclient/main.qml:43:9: Cannot assign to non-existent property "onTextMessageReceived"

我有一个这样的 QML 文件

****************************************************************************/
import QtQuick 2.0
import QtWebSockets 1.0
import Qt.Comm 2.0
Rectangle {
width: 360
height: 360

TCPSocketConnection{
id: socket
url: "ff"
onTextMessageReceived: {
console.log("On Recieve: " + messsage)
}

}

}

TCPSocketConnection定义如下

qmlRegisterType<TCPSocketConn>("Qt.Comm", 2, 0, "TCPSocketConnection");

在 tcpsocketconn.h 中

#ifndef TCPSOCKETCONN_H
#define TCPSOCKETCONN_H

#include <QQuickItem>


class TCPSocketConn : public QQuickItem
{

Q_PROPERTY(QString url READ url WRITE a_1 NOTIFY a_2)
Q_PROPERTY(QString message READ message WRITE a_3 NOTIFY textMessageRecieved)
Q_PROPERTY(int status READ status WRITE a_4 NOTIFY statusChanged)

public:
explicit TCPSocketConn(QQuickItem *parent = 0);

QString url();
QString message();
int status();

signals:
void a_2();
void textMessageReceived();
void statusChanged();

public slots:
void a_1(QString);
void a_3(QString);
void a_4(int);
};

#endif // TCPSOCKETCONN_H

带有占位符的cpp文件

#include "tcpsocketconn.h"

TCPSocketConn::TCPSocketConn(QQuickItem *parent) : QQuickItem(parent)
{

}

QString TCPSocketConn::url(){
return "";
}

QString TCPSocketConn::message(){
return "";
}

int TCPSocketConn::status(){
return 0;
}

void TCPSocketConn::a_1(QString d){

}

void TCPSocketConn::a_3(QString d){

}
void TCPSocketConn::a_4(int s){

}

void TCPSocketConn::textMessageReceived(){

}

void TCPSocketConn::statusChanged(){

}
void TCPSocketConn::a_2(){

}

最佳答案

你错过了 Q_OBJECT宏观;仅仅派生自 QObject 子类是不够的:

The Q_OBJECT macro must appear in the private section of a class definition that declares its own signals and slots or that uses other services provided by Qt's meta-object system.

还有 this paragraph :

Notice that the Q_OBJECT macro is mandatory for any object that implements signals, slots or properties. You also need to run the Meta Object Compiler on the source file. We strongly recommend the use of this macro in all subclasses of QObject regardless of whether or not they actually use signals, slots and properties, since failure to do so may lead certain functions to exhibit strange behavior.

对此有更详细的解释 here .

关于c++ - Qt - 无法分配给不存在的属性(自定义 C++ 类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35851891/

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