Firewall-Alien
Firewall-Alien

Reputation: 123

how to give a string as parameter to be inserted in a QStringListModel

am learning QT and am trying to populate a QStringList with a couple of elements that later populate a QListView

my first try from the docu was:

// Create model
model = new QStringListModel(this);

// Make data
List << "Java" << "C++" << "C";
// Populate our model
model->setStringList(List);
// Glue model and view together
ui->listView->setModel(model);

so far so good... I can see my List with all the elements I populate...

now in the same class where am doing that am trying to now defined a function that let me add new elements to the list...

so my 1st idea was defining something like

void MainWindow::addNewLanguage(QString& item)
{
    List << item;
    model->setStringList(List);
}

but(and here comes my question...) I am only able to call my function by doing

QString x( "Php" );
w1.addNewLanguage( x );

I would like to instead dom something more nice like:

w1.addNewLanguage( "Pascal" );

no need to define a new object of the QString...

but doing that breaks the compilation with the msg

C:\Users\xxx\WorspaceQT\untitled4\main.cpp:25: error: invalid initialization of non-const reference of type 'QString&' from an rvalue of type 'QString' w1.addNewLanguage( "x2" ); ^

anything I can do to address this??

thanks! :)

Upvotes: 0

Views: 205

Answers (1)

m7913d
m7913d

Reputation: 11072

The error message already gives you a great hint:

invalid initialization of non-const reference of type 'QString&' from an rvalue of type 'QString'

Therefore, you should define addNewLanguage as:

void MainWindow::addNewLanguage(const QString& item)

or alternatively:

void MainWindow::addNewLanguage(QString item)

Have a look at this post for an explanation why a non-const reference is not allowed to a temporary object.

Note that the second approach is not (much) slower than the first one as QString is implicitly shared.

Upvotes: 1

Related Questions