如何在 Qt 中复制对象? [英] How do I copy object in Qt?

查看:60
本文介绍了如何在 Qt 中复制对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Qt 并且有一些真正的基本问题.我创建了自己的小部件 MyTest,它有一个变量 obj.我需要从小部件外部的对象设置这个变量 obj 以便变量被复制而不仅仅是指向另一个对象的指针.我收到一条错误消息,但不知道如何做这些基本的事情.这是我正在使用的代码:

MyTest.h:

class MyTest : public QWidget{Q_OBJECT民众:void setObj(QObject &inobj);QObject 对象;....}

MyTest.cpp:

void MyTest::setObj(QObject &inobj) {obj = inobj;//此处我收到错误消息:从‘QObject’非法访问受保护/私有成员‘QObject::operator=(const QObject &)’"}

main.cpp:

int main(int argc, char *argv[]){QApplication a(argc, argv);QObject *ob = new QObject();我的测试 w;w.setObj(*ob);}

解决方案

似乎复制构造函数和赋值运算符被禁用了.来自this.

无复制构造函数或赋值运算符

QObject 既没有复制构造函数也没有赋值运算符.这是设计使然.实际上,它们是被声明的,但是在带有宏 Q_DISABLE_COPY() 的私有部分中.事实上,所有从 QObject 派生的 Qt 类(直接或间接)都使用这个宏来声明它们的复制构造函数和赋值运算符是私有的.推理可以在关于 Identity 的讨论中找到Qt Object Model 页面上的 vs Value.>

主要结果是您应该使用指向 QObject(或 QObject 子类)的指针,否则您可能会试图将 QObject 子类用作值.例如,如果没有复制构造函数,就不能使用 QObject 的子类作为要存储在容器类之一中的值.您必须存储指针.

I'm using Qt and have some real basic problems. I have created my own widget MyTest that have a variable obj. I need to set this variable obj from an object outside of the widget so that the variable is copied not just a pointer to another object. I get an error message and can't figure out how to do this basic stuff. This is the code I'm using:

MyTest.h:

class MyTest : public QWidget
{
    Q_OBJECT

    public:
        void setObj(QObject &inobj);

        QObject obj;
    ....
}

MyTest.cpp:

void MyTest::setObj(QObject &inobj) {
    obj = inobj; //HERE I get the error message: "illegal access from 'QObject' to protected/private member 'QObject::operator=(const QObject &)'"
}

main.cpp:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QObject *ob = new QObject();

    MyTest w;
    w.setObj(*ob);
}

解决方案

It seems the copy constructor and assignment operator are disabled. From this.

No copy constructor or assignment operator

QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in a private section with the macro Q_DISABLE_COPY(). In fact, all Qt classes derived from QObject (direct or indirect) use this macro to declare their copy constructor and assignment operator to be private. The reasoning is found in the discussion on Identity vs Value on the Qt Object Model page.

The main consequence is that you should use pointers to QObject (or to your QObject subclass) where you might otherwise be tempted to use your QObject subclass as a value. For example, without a copy constructor, you can't use a subclass of QObject as the value to be stored in one of the container classes. You must store pointers.

这篇关于如何在 Qt 中复制对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆