1
votes

I want to align text as follow on a QLabel:

name         : value
more         : other value
longer name  : value

It is easily done as follow

QString str;
str += "name\t\t: value\n";
str += "more\t\t: other value\n"
str += "longer name\t: value"

The question is, if I do not know the string pairs beforehand, is there a way in Qt to determine how many \t-chars must each string get so that they align on the : (if tabs are the only option)?

I can't use QString::arg() since the text is displayed on a GUI using non-constant-width-text. The issue here is that if I count the number of chars and set the fieldWidth the : does not align since the width of each char is not the same (changing the font is not an option)

I have tried some logic to count and then 'guess' the number of tabs to insert, which works in general but there might be some corner cases where it might not work.

I can also not make use of any other widgets since the code has only access to the one QLabel* that it must update.

2
you can use setw instead of tabs (would need to pipe it into a stringstream and then extracting the string from the stream)463035818_is_not_a_number
Another idea is use three labels per string; first label you make it right align, second align is center align and third label is left aligned. And then group them together or if you want to keep your original style make the first label left alignGurushant
I may have misunderstood but... the real problem here is actually the fact that the font being used is (or might be) proportionally spaced? If it weren't for that then a simple character count would suffice. Sorry if I'm stating the obvious.G.M.

2 Answers

2
votes

I think an alignment using a "white space" characters may fail if a font used is not monospace.

You should use QGridLayout or, if you really need to archive this using only one QLable, you may align text using html tags (table, tr, td).

0
votes

I would solve this problem in the way I describe below. For the sake of simplicity I just print out the output in the requested format, but you can modify the function on your own to set the label's text:

// Prints out the content as an aligned table
static void print(const QList<QPair<QString, QString>> &input)
{
  // Calculate the longest name.
  int longestName = 0;
  for (const auto &i : input) {
    longestName = std::max(longestName, i.first.length());
  }

  // Print out the content.
  for (const auto &i : input) {
    const auto &name = i.first;
    qDebug() << QString("%1%2 : %3")
                        .arg(name)
                        .arg(QString(longestName - name.length(), ' '))
                        .arg(i.second);
  }
}

I.e. at the beginning I calculate the length of the longest name and use that information for alignment.

And here is the usage example:

QList<QPair<QString, QString>> input =
{
  { "name", "value" },
  { "more", "other value" },
  { "longer name", "other value" },
};

print(input);