dani
dani

Reputation: 3887

How do I use QComboBox in relation with QVariant?

As I understood, QComboBox can hold a text (i.e. the name) and data (i.e. an object). My QComboBox should store QSizeF's, while showing nice names. Hence I would like to do something like this:

void fillComboBox() {
    ui->combobox->addItem("big", QVariant(QSizeF(600,400)));   
    ui->combobox->addItem("medium", QVariant(QSizeF(300,300)));   
    ui->combobox->addItem("small", QVariant(QSizeF(100,200)));
}

The problem is, that QVariant takes a QSizeF by const reference and not by value/move. After return, the reference will therefore dangle.

What is the correct way to do that? If I've a type MyClass, thus a custom class and not a Qwhatever, how would I use QVariante with that?

Note: of course I could create the QSizeF on the heap - however, I would need to take care of the memory which I try to avoid. This is eventually the reason for my question.

Upvotes: 1

Views: 1137

Answers (1)

Jesper Juhl
Jesper Juhl

Reputation: 31447

You are seeing problems where there are none.

  1. A const& will keep the (in this case temporary) object it refers to alive until the reference itself goes out of scope.

  2. If you look at the implementation of QVariant you'll see that it copies the value.

There's no problem here - move along.

Upvotes: 3

Related Questions