Artifex12
Artifex12

Reputation: 11

QStandarditem reject QString in constructor

I'm programming with c++ in Qt. When i construct QStandardItem it don't accept the QString declared before:

    file_content = new QString(textstream->readAll().mid(10,2)) ;
    standard_model->setItem(0,0,new QStandardItem(file_content));

But when I tried QStandardItem("example") it works.

Upvotes: 0

Views: 71

Answers (1)

dtech
dtech

Reputation: 49279

Your problem is that you are using a dynamically allocated string. The constructor for QStandardItem expects a QString &, not a QString *.

Since the pointer is basically an integer, using a pointer confuses the compiler to resolve to the QStandardItem(int rows, int columns = 1) constructor.

It will work if you standard_model->setItem(0,0,new QStandardItem(*file_content)); but the appropriate thing would be to:

QString file_content = textstream->readAll().mid(10,2);
standard_model->setItem(0,0,new QStandardItem(file_content));

QString uses dynamic allocation internally and it is implicitly shared. There is ABSOLUTELY no reason to use dynamic allocation for it.

Don't use dynamic allocation unless you know you have to. In Qt, the rule of thumb (with very few exceptions) is if it is a QObject derived, you should allocate dynamically, as such objects have unique identity and cannot be copied, whereas Qt's container classes use CoW and are implicitly shared - they are very efficient to pass even by value and in most of the cases the proper thing would be to put them on the stack rather than on the heap.

Upvotes: 1

Related Questions