I have two classes set up, InputFile
and InputStream
. Both inherit QObject
, and are initialized with the Q_OBJECT
macro.
InputFile
contains a QMap<int,InputStream*>
, creates InputStream
objects and inserts them in the QMap
.
InputStream
is initialized with an explicit constructor, then inserted into the map like this:
InputStream myStream = InputStream(this, *myParameter);
_myMap.insert(myInt, *myStream);
The compiler returns a few errors in reference to my insertion call:
/opt/Qt5.5.0/5.5/gcc/include/QtCore/qobject.h:461: error: 'QObject::QObject(const QObject&)' is private
Q_DISABLE_COPY(QObject)
^
/home/myusername/Documents/Projects/MyProject/inputfile.cpp:17: error: no match for 'operator*' (operand type is 'InputStream')
_myMap.insert(myInt, *myStream);
^
I then tried to initialize InputStream
as a pointer:
InputStream *myStream = InputStream(this, *myParameter);
In this case, the compiler returns the following error:
/home/myusername/Documents/Projects/MyProject/inputfile.cpp:16: error: cannot convert 'InputStream' to 'InputStream*' in initialization
InputStream *myStream = InputStream(this, *myParameter);
^
I have also tried to use a reference ( &
) in the insert call, but this still returns the first error.
How can I initialize my object as needed and insert it in my QMap
?
First error means that you can't copy QObject subclass, so you should use pointer to it (as you said in the beginning), so you need your second approach, but you forgot allocate memory and construct object( you forgot new keyword). So use just:
InputStream *stream = new InputStream(...);
If _myMap
is really a QMap<int,InputStream*>
then you should insert just the raw pointer, not the object pointed at by the pointer:
_myMap.insert(myInt, myStream);
The error message is telling you that you cannot copy QObjects. Here is an explanation as to why QObjects are not copyable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.