Search code examples
c++labelqwt

Qwt : align center the date/time label text on an bottom axis


With Qwt, I want that the time and the date are both center under the tick under a bottom axis, but the time is still on the left side like in this picture :

enter image description here

I have tried to use

QwtDateScaleDraw::setLabelAlignment(Qt::AlignHCenter|Qt::AlignBottom);

But the time is still on the left.

I have tried to subclass the QwtScaleDraw like this:

class MyDateScaleDraw:public QwtDateScaleDraw
{
public:
    QwtText label(double value) const override
    {
        QwtText txt=QwtDateScaleDraw::label(value);
        txt.setRenderFlags(Qt::AlignHCenter);
        return txt;
    }
};

But the time is still on the left side.

Somebody know how to center the time ?

UPDATE :

I have found in the source code of Qwt this:

const QwtText &QwtAbstractScaleDraw::tickLabel(const QFont &font, double value ) const
{
    QMap<double, QwtText>::const_iterator it = d_data->labelCache.find( value );
    if ( it == d_data->labelCache.end() )
    {
        QwtText lbl = label( value );
        lbl.setRenderFlags( 0 );
        lbl.setLayoutAttribute( QwtText::MinimumLayout );

        ( void )lbl.textSize( font ); // initialize the internal cache

        it = d_data->labelCache.insert( value, lbl );
    }

    return ( *it );
}

It is the method who, I guess, generate the QwtText Label.

It seems that the line 8 set the render flags to '0'. May be it why changing the renderFlags of the label don't change the alignement of the label under the tick.

What do you think ?


Solution

  • Found !!!

    Instead of override the method Qt Code: Switch view

    label(double value)
    

    To copy to clipboard, switch view to plain text mode .

    I have to override the drawLabel method of QwtDateScaleDraw :

    void drawLabel( QPainter *painter, double value ) const override
            {
                    QwtText lbl = tickLabel( painter->font(), value );
                    if ( lbl.isEmpty() )
                        return;
    
                    lbl.setRenderFlags(Qt::AlignCenter); //<---- add this line 
    
                    QPointF pos = labelPosition( value );
    
                    QSizeF labelSize = lbl.textSize( painter->font() );
    
                    const QTransform transform = labelTransformation( pos, labelSize );
    
                    painter->save();
                    painter->setWorldTransform( transform, true );
    
                    lbl.draw ( painter, QRect( QPoint( 0, 0 ), labelSize.toSize() ) );
    
                    painter->restore();
    
            }
    

    To copy to clipboard, switch view to plain text mode

    And after the label is really center !

    The setRenderFlags method can not do the job !!!