Search code examples
qtvariablessignals-slotspreserve

Preserving values between slots or functions in QT


I'm working with QT. Is there a way to preserve values between slots or functions in general? Just to keep it simple, let's say my form has three buttons on a toolbar and a line edit. I need the first button to set the value "1" to a variable, and the second button to set "2" to a variable. The third button takes this variable and shows it inside the line edit.

So if I press the first button and then the third the line edit will show the number "1". If I press the second button and then the third the line edit will show the number "2". Basically this would make third button's slot look up the variable that was set by either the first or the second button and then display it. I realize this isn't the perfect example, but I think it illustrates the concept.

The way's I've tried to think to do it are:

  1. They way I remember from a VB class I took in school... Create a hidden line edit and store the value there until I need it. Sadly this will mean lots and lots of hidden line edits on a complex project. Yuck.

  2. Create a global variable in the int main() function and set that variable across all the functions. That can get confusing and anything can access it. So that can be messy.

  3. I've noticed that QT for a desktop application appears to have a class called "ui". I've thought of creating my own class with a getter and setter and inheriting everything out of ui... I believe this would work but it seems like overkill.

  4. Save the information in a tmp file and read it. This seems like it could also be a pain when I just need short term variables.

Is there a simple way to accomplish this task?


Solution

  • You can use a QSignalMapper and connect the first and second buttons to it:

    signalMapper = new QSignalMapper(parent);
    connect(firstButton, SIGNAL(clicked()), signalMapper, SLOT(map()));
    connect(secondButton, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(firstButton, 1);
    signalMapper->setMapping(firstButton, 2);
    

    You then connect signalMapper's mapped(int) signal to your slot:

    connect(signalMapper, SIGNAL(mapped(int)), yourObj, SLOT(yourSlot(int)));
    

    When the first button is clicked, your slot will be called with the value 1 as its argument. When the second button is clicked, 2 will be passed to your slot. You can then save the passed value wherever you like (like in a member variable of yourObj.)