Pico
Pico

Reputation: 303

Alias of a variable in C++/Qt?

Is there a way to create an alias of a UI variable in Qt ?

this var

ui->combobox->currentIndex()

becoming for example

index

so whenever in my code I call index I get the value of ui->combobox->currentIndex() even if she changed during two calls.

I tried this but I always get the same value, the one during the initialization.

int *index = 0;
index = (int *)ui->combobox->currentIndex() // equals -1 this time;
(int)index; //always return -1 but if I do ui->combobox->currentIndex() it returns 0;

The goal is to reduce the length of very long statement.
Thanks :)

Upvotes: 0

Views: 333

Answers (2)

dunc123
dunc123

Reputation: 2723

Possibly the best way do do this would be to add an inline function that returns the current index:

inline int MainWindow::myIndex() const
{
  return ui->combobox->currentIndex();
}

Then you can call myIndex() whenever you need the value.

Or simply assign a local variable before the statement you are using it in:

int const index = ui->combobox->currentIndex();

Upvotes: 6

Robadob
Robadob

Reputation: 5349

You want to use the preproccessor macro #define

#define <alias> <replacement>

Is the format you use, then at compile the compiler replaces all instances of your alias.

http://www.cplusplus.com/doc/tutorial/preprocessor/

Upvotes: 0

Related Questions