c++ - Qt - 使用 QString::arg 将文本对齐到列中

标签 c++ string qt format

我正在使用 QString::arg 格式化字符串,我需要将字符串格式化为列。例如:

78.0    78.0    78.0
0.0     0.0     78.0
69.0    56.0    0.0

现在我对每一列使用d += QString("%1").arg("78.0", -50, ' '); 然后 d += '\n' 用于新行。

唯一的问题是空格字符与数字的宽度不同,所以会出现错位:

misalignment

我只想知道如何将文本对齐到列中?谢谢。

最佳答案

您可以使用 QTextEdit 及其富文本布局功能。然后您可以以编程方式生成一个 html 表:

// https://github.com/KubaO/stackoverflown/tree/master/questions/textedit-columns-37949301
#include <QtWidgets>

template <typename It, typename F>
QString toTable(It begin, It end, int columns, F && format, 
                const QString & attributes = QString()) {
   if (begin == end) return QString();
   QString output = QStringLiteral("<table %1>").arg(attributes);
   int n = 0;
   for (; begin != end; ++begin) {
      if (!n) output += "<tr>";
      output += "<td>" + format(*begin) + "</td>";
      if (++n == columns) {
         n = 0;
         output += "</tr>";
      }
   }
   output += "</table>";
   return output;
}

如果您要将大量数据加载到 QTextEdit 中,您可以在单独的线程中创建一个 QTextDocument,在那里填充它,然后将其传输到 QTextEdit:

#include <QtConcurrent>

void setHtml(QTextEdit * edit, const QString & html) {
  QtConcurrent::run([=]{
    // runs in a worker thread
    auto doc = new QTextDocument;
    doc->setHtml(html);
    doc->moveToThread(edit->thread());
    QObject src;
    src.connect(&src, &QObject::destroyed, qApp, [=]{
      // runs in the main thread
      doc->setParent(edit);
      edit->setDocument(doc);
    });
  });
}

以类似的方式,也可以将 QTextEdit 的呈现委托(delegate)给工作线程,尽管这是我必须在单独的问题中解决的问题。该方法类似于 the one in this answer .

让我们开始使用它:

int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   double const table[] {
      78.0,    78.0,    78.0,
      0.0,     0.0,     78.0,
      69.0,    56.0,    0.0};
   QTextEdit edit;
   setHtml(&edit, toTable(std::begin(table), std::end(table), 3,
                          [](double arg){ return QString::number(arg, 'f', 1); },
                          "width=\"100%\""));
   edit.setReadOnly(true);
   edit.show();
   return app.exec();
}

关于c++ - Qt - 使用 QString::arg 将文本对齐到列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37949301/

相关文章:

c++ - 为什么 Visual Studio 在这种情况下不执行返回值优化 (RVO)

c++ - 将新 C++ 转换为旧 C++

c++ - 可以在不使用数组的情况下对字符串变量的内容进行排序吗?

c++ - 无法将QString转换为Const Char *

qt - 单击关闭按钮后取消关闭 QWidget

c++ - 如何让带有 QSqlTableModel 的 QTableView 具有复选框和多行?

c++ - OneOfAType 容器——将每个给定类型的容器存储在一个容器中——我在这里是否偏离了基地?

java - 在 Java 中查找特定长度/格式的子字符串

Java单词反转

c - C 上的字符串行为