2

I am trying to pass a QLabel as a parameter to another function that is supposed to change the style of the label:

main
{
...
setSeatColor(ui->lblPan2Seat5B, 2);

}


void setSeatColor(QLabel& lbl, int i)
{
   if(i == 1)
   {
    lbl.setStyleSheet("QLabel { background-color : blue; color : white; }");
   }
   else if(i == 2)
   {
    lbl.setStyleSheet("QLabel { background-color : red; color : white; }");
   }
   else if(i == 3)
   {
    lbl.setStyleSheet("QLabel { background-color : green; color : white; }");
   }
   else
   {
    lbl.setStyleSheet("QLabel { background-color : rgb(240,240,240); color : back; }");
   }
}

The error in the function:

"No matching function for call to setSeatColor(QLabel*&,int)"

Your help is much appreciated!

Igor Tupitsyn
  • 1,193
  • 3
  • 18
  • 45

1 Answers1

3

You pass a QLabel pointer to a function that takes a QLabel&, so replace this call:

setSeatColor(ui->lblPan2Seat5B, 2);

with this one (notice the dereference operator *)

setSeatColor(*ui->lblPan2Seat5B, 2);

//you can use extra parentheses for your colleagues, so that they can understand what are you doing there: setSeatColor( *(ui->lblPan2Seat5B), 2); - that way is a little clearer that you intend to dereference the lblPan2Seat5B not the ui that is dereferenced by the -> operator

Zlatomir
  • 6,964
  • 3
  • 26
  • 32
  • Changed to: setSeatColor(*(ui->lblPan2Seat5B),2); Now it gives the following error: Undefined reference to MainWindow::setSeatColor(QLabel&, int). Hm.... – Igor Tupitsyn Nov 16 '13 at 21:23
  • Ah! Found. A stupid error: void MainWindow::setSeatColor(QLabel& lbl, int i). Thanks a lot. By the way, a question about the (*ui->lblPan2Seat5B) pointer. Do I need to specifically delete it myself in the destructor or it will be deleted when the main class closes automatically? Thanks! – Igor Tupitsyn Nov 16 '13 at 22:19
  • You don't have to delete that, that pointer holds the address of an object that is a child of the _ui_ (actually the object that has it's address stored into the ui pointer), _ui_ is deleted in your class destructor and that delete triggers the delete of all it's children. For more information see the documentation: https://qt-project.org/doc/qt-4.8/objecttrees.html – Zlatomir Nov 16 '13 at 22:31
  • Great. This is what I thought since I am not creating an object on the heap. Just double checked. Thank you so much! – Igor Tupitsyn Nov 16 '13 at 22:35
  • With QObjects and classes derived from QObject you don't really need to call delete, basically you need to call delete for (or allocate on a stack) those QObjects that don't have a parent (and don't get a parent later, example you can create a QLabel without a parent, but when you put it into a layout it gets the layout's parent) – Zlatomir Nov 16 '13 at 22:41