PDA

View Full Version : Function to set bg-color & text of label and pass instance of an object



Terreox
7th February 2012, 21:00
Hi there,

i program an Operationcenter for our local fire department (our younger members ( < 13 years old) use it on special training courses).
To monitor all vehicles' state i designed a Status-Monitor. If a vehicle changes his state (e.g. has an accident and is not ready for any incidents) there are several things to do for the program:
1.) Change color of a label
2.) Change text of a label

These tasks are very simple to program but now to my real problem.
There are 9 possible states. Each vehicle has its own groupbox and combobox. With the combobox and a pushbutton the user can choose the current state and set it.

Here is a screenshot:
7371

Now to my question:
Is there a possible way to create a function that gets two arguments (id of state and instance of label to where colour and text shall be applied to) instead of creating a function like this (its just the beginning of a function not the complete one!):

void ControlPanel::setStatus(int id, int boxId)
{
if(boxId == 1){
switch(id){
case 1:
this->lblStatus1->setStyleSheet("background-color: rgb(181, 217, 164);");
this->lblStatus1->setText("1");
break;
case 2:
this->lblStatus1->setStyleSheet("background-color: rgb(121, 185, 92);");
this->lblStatus1->setText("2");
break;
case 3:
this->lblStatus1->setStyleSheet("background-color: rgb(244, 209, 81);");
this->lblStatus1->setText("3");
break;
case 4:
this->lblStatus1->setStyleSheet("background-color: rgb(239, 174, 77);");
this->lblStatus1->setText("4");
break;
case 5:
this->lblStatus1->setStyleSheet("background-color: rgb(239, 174, 77);");
this->lblStatus1->setText("4");
break;
}
}
}

I mean the main thing i want to know is how i can pass an instance of an object to a function so that i dont need the if(boxId == 1) thing?
Are there maybe better and more efficient ways? Dont want to waste 100 lines of code if there is a better solution with less lines :)


Greetz

ChrisW67
7th February 2012, 22:04
Try passing the pointer to the label, i.e.lblStatus1 ,lblStatus2 etc., rather than the index:


void ControlPanel::setStatus(int id, QLabel *label) {
Q_ASSERT(label); // to catch yourself if you pass a NULL during development
switch(id) {
case 1:
label->setText(...);
label->setStyleSheet(...);
break;
case 2:
// stuff for id 2
break;
....
default:
// Unexpected value?
break;
}
}

You might then ask yourself if there are more efficient ways to do this as well, e.g. is the label text is the same as the id number, can you derive or lookup the colour value?