-   Programming (
-   -   Combine number and text (

Ephracis 11-17-2004 10:39 AM

Combine number and text
I have a this code right now:

QLabel *label = new QLabel("text", this, "name");
The function QLabel takes three arguments, the first is the actual text, the second is the parent widget and the last (the interesting) is the name of the label (not the name of the variable).

The question is really easy (I think). I don't know how many of these I will need, so I would get the number of labels at runtime and then I would like to call them "name1", "name2", etc by just using a for-loop, that would produce like:


for (int i = 0; i<num; i++)
  QLabel ? = new QLabel("text", this, ?);


QLabel *label1 = new QLabel("text", this, "name1");
QLabel *label2 = new QLabel("text", this, "name2");
QLabel *label3 = new QLabel("text", this, "name3");
QLabel *labeln = new QLabel("text", this, "namen");

How can I do this, combine both the string "text" with the integer i in the argument, and also combine the text "label" with the same number in the name of the variable.

Hivemind 11-17-2004 11:02 AM

A simple solution would be to have a function that returns the next label name.

Untested code:

const std::string& next_label = get_next_label_name();

QLabel *label = new QLabel("text", this, next_label.c_str());

Where get_next_label_name() is defined as:

std::string get_next_label_name()
  static int count = 1;
  std::ostringstream oss;

  oss << "Name " << count++;

  return oss.str();

Ephracis 11-17-2004 11:46 AM

I still have the problem with the variable-name. This one is really important. Is there even a solution to this? Can I create like three variables called var1, var2, var3 with a for-loop, without using arrays.

Hko 11-17-2004 12:13 PM

You simply cannot do it that way.
You can, however, use an array or a QList of pointers to QLabel's.
An array would look something like this:

QLabel *labels[100];

for (int i = 0; i < 100; ++i) {
    std::ostringstream oss;
    oss << "Name " << i;

    labels[i] = new QLabel("text", this, oss.str());

All times are GMT -5. The time now is 12:31 PM.