Incorrect Bounding Rect?
-
Hi, I have a code to generate a label for axis:
void npi::PlotWidget::createLabelForAxis(Axis* axis) { // labelSize is QSize, labelFont.font is "Courier", labelFont.metrics is QFontMetrics for labelFont.font, axis->label is QString, colors.text is Qt::black if(axis != nullptr) { axis->labelSize.setHeight(labelFont.metrics.height()); axis->labelSize.setWidth(labelFont.metrics.boundingRect(axis->label).width()); axis->labelPix = QPixmap{axis->labelSize}; axis->labelPix.fill(QColor{255, 0, 0, 50}); QPainter painter(&axis->labelPix); painter.setPen(QPen{colors.text}); painter.setFont(labelFont.font); painter.drawText(0, 0, axis->labelSize.width(), axis->labelSize.height(), Qt::AlignCenter, axis->label); painter.drawRect(labelFont.metrics.boundingRect(axis->label)); qDebug() << axis->label << labelFont.metrics.boundingRect(axis->label); } }When it is run it draws:

and outputs:
"Time [s]" QRect(0,-14 75x18)Why is it giving me
-14as the y position of the bounding rect? Also, the left sideTin the drawn label is truncated, why is that? Since I am making thelabelPixthe width of theboundingRectof label string and usingQt::AlignCenterthe entire text should fit inside thelabelPix. -
Hi, I have a code to generate a label for axis:
void npi::PlotWidget::createLabelForAxis(Axis* axis) { // labelSize is QSize, labelFont.font is "Courier", labelFont.metrics is QFontMetrics for labelFont.font, axis->label is QString, colors.text is Qt::black if(axis != nullptr) { axis->labelSize.setHeight(labelFont.metrics.height()); axis->labelSize.setWidth(labelFont.metrics.boundingRect(axis->label).width()); axis->labelPix = QPixmap{axis->labelSize}; axis->labelPix.fill(QColor{255, 0, 0, 50}); QPainter painter(&axis->labelPix); painter.setPen(QPen{colors.text}); painter.setFont(labelFont.font); painter.drawText(0, 0, axis->labelSize.width(), axis->labelSize.height(), Qt::AlignCenter, axis->label); painter.drawRect(labelFont.metrics.boundingRect(axis->label)); qDebug() << axis->label << labelFont.metrics.boundingRect(axis->label); } }When it is run it draws:

and outputs:
"Time [s]" QRect(0,-14 75x18)Why is it giving me
-14as the y position of the bounding rect? Also, the left sideTin the drawn label is truncated, why is that? Since I am making thelabelPixthe width of theboundingRectof label string and usingQt::AlignCenterthe entire text should fit inside thelabelPix.It seems, that you are painting on
PlotWidgetusingQPainteroutside of itspaintEvent. This can lead to unwanted bahavior and shouldn't be done.In your case, your text won't
update()(is redrawn) together with the rest of the widget, for example, when resizing. -
It seems, that you are painting on
PlotWidgetusingQPainteroutside of itspaintEvent. This can lead to unwanted bahavior and shouldn't be done.In your case, your text won't
update()(is redrawn) together with the rest of the widget, for example, when resizing.