简体   繁体   English

将格式化的文本显示为QTextEdit,就像在C的printf中一样

[英]display formatted text to QTextEdit like in C's printf

I would like to display a double in qttextedit. 我想在qttextedit中显示一个双精度。 For example, if i have 例如,如果我有

double f = 0.0;

and I do 而我

ui.textEdit->insertPlainText("f = "+ QString::number(f ));

I get 我懂了

f =0 f = 0

I would like to show 我想展示

f = 0.000 f = 0.000

with as many decimal places as I want.. 用我想要的小数位数。

Anyway to do that.. 不管怎么说

I can not test it right now, but I would try ui.textEdit->insertPlainText(QString("f = %1").arg(f, 5, 'g', -1, QLatin1Char('0'))); 我现在无法对其进行测试,但是我会尝试ui.textEdit->insertPlainText(QString("f = %1").arg(f, 5, 'g', -1, QLatin1Char('0')));

See this for more details. 请参阅了解更多详情。

You have at least two Qt options: 您至少有两个Qt选项:

1) QString & QString::sprintf ( const char * cformat, ... ) 1) QString和QString :: sprintf(const char * cformat,...)

QString result;
double f = 0.000;
result.sprintf("%.3f", f);
ui.textEdit->insertPlainText(result);

2) QString QString::arg ( double a, int fieldWidth = 0, char format = 'g', int precision = -1, const QChar & fillChar = QLatin1Char( ' ' ) ) const 2) QString QString :: arg(double a,int fieldWidth = 0,char format ='g',int precision = -1,const QChar&fillChar = QLatin1Char(''))const

double f = 0.000;
QTextStream standardOutput(stdout);
standardOutput << QStringLiteral("f = %1").arg(f, 0, 'f', 3) << "\n";

Here you can find my test code that is easy to run in order to verify. 在这里,您可以找到易于运行的测试代码以进行验证。

main.cpp main.cpp中

#include <QString>
#include <QTextStream>

int main()
{
    QString result;
    double f = 0.000;
    result.sprintf("%.3f", f);
    QTextStream standardOutput(stdout);
    standardOutput << QStringLiteral("f = %1").arg(f, 0, 'f', 3) << "\n";
    standardOutput << "f = " << result << "\n";
    return 0;
}

main.pro main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run 生成并运行

qmake && make && ./main

Output 产量

f = 0.000
f = 0.000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM