2014-02-20 75 views
0

这是我正在为this other question工作的解决方案。文本需要在给定的rect中水平和垂直居中。为什么QRect :: moveCenter无法按预期工作?

void 
draw_text_label (QPainter & p, const QString & text, QRectF rect) 
{ 
    // Work in unscaled coordinates (see linked question if you're curious) 

    p .save(); 
    assert (false == p .transform() .isRotating()); 
    rect = p .transform() .mapRect (rect); 
    p .resetTransform(); 

    // Scale to fit 

    set_font_size (p, font_size_to_fit (p, text, rect)); 

    QRectF text_rect = p .fontMetrics() .tightBoundingRect (text); 

    //////////////////////////// 
    // this line ALMOST works // 
    //////////////////////////// 

    text_rect .moveCenter (rect .center()); 

    // Draw 

    p .translate (text_rect .left(), text_rect .bottom()); 

    p .setPen (Qt :: red); 
    p .drawText (0, 0, text); 
    p .drawRect (0, 0, text_rect .width(), -text_rect .height()); 

    p .restore(); 
} 

这是由

void 
draw_thingy (QRectF rect) 
{ 
    p .setPen (Qt :: white); 
    p .drawRect (rect); 

    float m = MARGIN * 0.5; 
    draw_text_label (thingy_text, rect .adjusted (m,m,-2*m,-2*m)); 
} 

总之叫,在给定rect白表示,在text_rect以红色表示。

enter image description here

正如你在这个测试图像(link in case the inline image dies)看到,红色矩形不是很集中。这不仅仅是一个舍入误差。

这是怎么发生的?

回答

0

使用DrawText中的对齐值Qt::AlignCenter将文本居中在rect中。不需要进行直接计算。

+0

这似乎是产生完全相同的结果。 – spraff

+0

可能与您应用于该画家的变换有关。尝试注释掉所有的转换代码 – cppguy

相关问题