0

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! :)

  • 3
    change `void MainWindow::addNewLanguage(QString& item)` to `void MainWindow::addNewLanguage(const QString& item)` – drescherjm Aug 30 '17 at 16:00
  • 2
    it does not work because Pascal is not a new language :P Joking aside, here you can find an explanation: https://stackoverflow.com/questions/13826897/why-not-non-const-reference-to-temporary-objects – 463035818_is_not_an_ai Aug 30 '17 at 16:03
  • @Firewall-Alien Try to construct a minimal question avoiding all irrelevant information (`QStringList`, ...), see [mcve] and [ask]. – m7913d Aug 30 '17 at 16:11

1 Answers1

1

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.

m7913d
  • 10,244
  • 7
  • 28
  • 56