我正在使用 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'
用于新行。
唯一的问题是空格字符与数字的宽度不同,所以会出现错位:
我只想知道如何将文本对齐到列中?谢谢。
最佳答案
您可以使用 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/