简体   繁体   中英

Alignment problems while painting QString onto the QImage object

I want to create a string that will be printed on the screen. I will update this string every time values of the variables printed will change. The number of digits in each number can be different and sign of each number may change with time. What I want to be constant is numbers precision. The output I expect is sth like this (each line correspond to the same string, only updated):

X:  453.432  Y:  543.432
X:   -5.432  Y:    4.432
X:   43.234  Y: -123.423

Namely, the letters and the dot should always stay in the same place on the screen.

At the moment I use this code for string updates but position of the Y and dots vary if number of digits change. Is there a simple way to implement it?

text = QString("X: %1   Y: %2").arg( QString::number( x(), 'f', 3 ),
                                     QString::number( y(), 'f', 3 ) );

------------------ EDIT ------------------

Following the answer I created a string with constant spacing (constant length actually). It didn't solve my problem fully though.

In the next step I take the string text and using QPainter I paint it onto QImage object. The problem that I encounter here is that though the string length is always the same the width of numbers is different than the width of spaces (' ') and '-' sign painted by QPainter . So when the number of digits changes the positions of dots and 'Y' symbol changes as well.

Here is the code that I use for image creation:

QImage img( 100, 100, QImage::Format_ARGB32_Premultiplied ); 
img.fill( Qt::transparent );

QPainter painter( &img );

QPen pen;
pen.setColor( Qt::darkBlue );
painter.setPen(pen);

QFont font = painter.font();
font.setBold( true );
font.setPointSize( 10 );
painter.setFont( font );

QString text = QString("X:%1   Y:%2")
    .arg( x(), 9, 'f', 3, ' ' )
    .arg( y(), 9, 'f', 3, ' ' );
painter.drawText( QPointF(0, 50), text );
painter.end();

You can use this signature of the arg method:

// arg(double a, int fieldWidth, char format, int precision, QChar fillChar)
QString formated = QString("X:%1 Y:%2")
    .arg(x(), 9, 'f', 3, ' ')
    .arg(y(), 9, 'f', 3, ' ');

For your second problem, I solve it by changing the font family.

font.setFamily("Courier");

These are my results:

Default font:
默认字体

Courier font:
信使字体

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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