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

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

问题描述

我使用Qt并有一些真正的基本问题。我创建了我自己的小部件MyTest有一个变量 obj 。我需要从窗口小部件之外的对象设置此变量 obj ,以便复制变量而不仅仅是指向另一个对象的指针。我得到一个错误消息,不能弄清楚如何做这个基本的东西。这是我使用的代码:

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:

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.

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

QObject既没有复制构造函数也没有赋值运算符。这是设计。实际上,它们被声明,但在一个私有部分与宏Q_DISABLE_COPY()。事实上,从QObject(直接或间接)派生​​的所有Qt类使用此宏来声明其复制构造函数和赋值运算符为私有。推理可在的讨论中找到 Qt对象模型页面上的标识与值。

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.

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

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天全站免登陆