2

I am trying to add a QPixmap to a QLabel taken from another QLabel but there is an error :

Here is the code

const QPixmap *tempPix = new QPixmap("");
tempPix = (label1->pixmap());
label2->setPixmap(tempPix);  //error cannot convert from const QPixmap* to const QPixmap&

and if I do it like this:

const QPixmap tempPix("");
tempPix = (label1->pixmap()); //error cannot convert QPixmap and QPixmap*
label2->setPixmap(tempPix);
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Ammar H Sufyan
  • 97
  • 1
  • 3
  • 13

2 Answers2

3

To copy data from a pointer object to an object you must use the *

QPixmap tempPix;
if(label1->pixmap()){
    tempPix = *label1->pixmap();
    label2->setPixmap(tempPix);
 }
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
1

You can write it in a single line as follows:

label2->setPixmap(*label1->pixmap());

Note that * will convert the pointer returned by pixmap() to a reference. The difference between both is explained in this thread.

Note that in your first example, the constructed QPixmap in the first line is never used and a memory leak occurs. The second line changes the pointer value, not the data of the newly constructed object.

Community
  • 1
  • 1
m7913d
  • 10,244
  • 7
  • 28
  • 56
  • 1
    Unfortunately, `QLabel::pixmap()` suffers from an API bug since `pixmap` is a value property, yet `pixmap()` and returns a pointer instead of the value itself. The pointer can be null, and this code has undefined behavior when `label1` has no pixmap :( – Kuba hasn't forgotten Monica May 22 '17 at 13:32
  • 1
    The safest way is indeed to check if `pixmap` is not null, but if the OP knows this is not the case, the check is not needed. – m7913d May 22 '17 at 14:01