Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Align QPainterPath



  • Hi there.
    Problem is: outline (stroke) text into qlabel.

    Reimplementing paintEvent for this

    ::paintEvent(QPaintEvent* event)
    {
    	QPainter painter (this);
    
    	QPainterPath path;
    
    	painter.setPen(Qt::green);
    	painter.setBrush(palette().windowText());
    	painter.setRenderHints(QPainter::Antialiasing);
    	painter.setFont(font());
    
    	QRectF bounds;
    	painter.drawText(contentsRect(), alignment(), text(), &bounds);
    
    //	path.addText(bounds.topLeft(), font(), text());
    	path.addText(56, 260, font(), text());
    	
    	painter.strokePath(path, QPen(QColor(255, 0, 0, 255), 2));
    }
    

    Got
    0_1539689127584_StereoControlCenter 2018-10-16 14.24.42.png

    So main problem is calculate aligns for path.addText. I'm try to found solution inside of QPainter, but drawText function looks too hard for understanding.

    bounds rect also not informative, cause it contains some unknown digits...

    How can i calculate Bottom left point of text? (or any other solution for text outlining except drawing text with bigger size :)



  • UPD:
    I write this method for drawing, looks good

    {
    	QLabel::paintEvent(event);
    
    	QPainter painter (this);
    
    	painter.setPen(Qt::green);
    	painter.setBrush(palette().windowText());
    	painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    	painter.setFont(font());
    
    	QRect font_rect = painter.fontMetrics().boundingRect(text());
    	QRect label_rect = contentsRect();
    	label_rect.adjust(margin(), margin(), -margin(), -margin());
    
    	int dx = label_rect.width() - font_rect.width();
    	int dy = label_rect.height() - font_rect.height();
    
    	int x = 0;
    	int y = 0;
    
    	if      (alignment() & Qt::AlignLeft)    x = label_rect.left();
    	else if (alignment() & Qt::AlignHCenter) x = label_rect.left() + dx / 2;
    	else if (alignment() & Qt::AlignRight)   x = label_rect.right() - font_rect.width();
    
    	if      (alignment() & Qt::AlignTop)     y = label_rect.top() + font_rect.height();
    	else if (alignment() & Qt::AlignVCenter) y = label_rect.top() + dy / 2;
    	else if (alignment() & Qt::AlignBottom)  y = label_rect.bottom();
    
    	QPainterPath path;
    	path.addText(x, y, font(), text());
    	
    	painter.fillPath(path, palette().windowText());
    	painter.strokePath(path, QPen(QColor(255, 0, 0, 50), 2));
    }
    

    0_1539696004806_StereoControlCenter 2018-10-16 16.19.04.png

    But i still dont understand the difference btw native paint event and my own