Search code examples
qtqpainter

how to get the end position of drawItemText in Qt


I am trying to customize a QPUshButton by subclassing it and overriding the paintEvent. I am writing the text, followed by the icon as below:

paintEvent(QPaintEvent *paint)
    {
         QStyleOption opt;
         opt.init(this);
         QPainter p(this);
        //Draw the base
         style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);

        //Draw the text
         style()->drawItemText(&p,this->rect(),Qt::AlignCenter,(this->palette()), true, this->text());

    //How do I make the image immediately follow the text

         if(!this->icon().isNull())
            //Draw the icon at 75% button height
            style()->drawItemPixmap(&p, this->rect(),Qt::AlignRight|Qt::AlignVCenter, this->icon().pixmap(this->rect().height()  * 0.75));

    }

I am center aligning the text, and right aligning the icon. However, this causes a gap between the text and the icon. Is there any way for me to draw the icon immediately after the text, instead of aligning?

In other words, is there any way to get the position where the drawItemText finished?


Solution

  • QStyle::itemTextRect() will tell you where the text will be laid down with given rectangle, font metrics and alignment.