qt 写字

Coordinate System

坐标系统

The coordinate system is controlled by the QPainter class. Together with the QPaintDevice and QPaintEngine classes, QPainter form the basis of Qt's painting system, Arthur. QPainter is used to perform drawing operations, QPaintDevice is an abstraction of a two-dimensional space that can be painted on using a QPainter, and QPaintEngine provides the interface that the painter uses to draw onto different types of devices.

The QPaintDevice class is the base class of objects that can be painted: Its drawing capabilities are inherited by the QWidget, QImage, QPixmap, QPicture, and QOpenGLPaintDevice classes. The default coordinate system of a paint device has its origin at the top-left corner. The x values increase to the right and the y values increase downwards. The default unit is one pixel on pixel-based devices and one point (1/72 of an inch) on printers.


默认是左上角为0, 0 点,向下向右增加。 显示器这种是以pixel为单位,打印机是point
image


坐标都是忽略 笔的宽度



void QPainter::drawText(const QRectF &rectangle, int flags, const QString &text, QRectF *boundingRect = nullptr)

写字到指定矩形内

查看文档有例子



QRectF QPainter::boundingRect(const QRectF &rectangle, int flags, const QString &text)

计算文字占用的矩形大小



下面代码,发现3种计算出来结果都一样

QPainter painter(this);
QFont font = painter.font();
font.setPixelSize(48);
painter.setFont(font);

const QRect rectangle = QRect(0, 0, 180, 50);
QRect boundingRect;
painter.drawText(rectangle, 0, tr("Hello中文"), &boundingRect);
qDebug()<<boundingRect;

QFontMetrics fm(font);
int pixelsWide = fm.horizontalAdvance("Hello中文");
int pixelsHigh = fm.height();
qDebug()<<pixelsWide<<pixelsHigh;

qDebug()<<painter.boundingRect(boundingRect,Qt::AlignLeft, "Hello中文" );

QPen pen = painter.pen();
pen.setStyle(Qt::DotLine);
painter.setPen(pen);
painter.drawRect(boundingRect.adjusted(0, 0, -pen.width(), -pen.width()));

pen.setStyle(Qt::DashLine);
painter.setPen(pen);
painter.drawRect(rectangle.adjusted(0, 0, -pen.width(), -pen.width()));

posted on 2022-09-09 15:38  katago  阅读(67)  评论(0编辑  收藏  举报