Qt obtains the printer DPI and calculates the actual print size of the font

The code is as follows, just take a note and it won’t be long-winded

QPrinter printer(QPrinter::HighResolution);
printer.setPrinterName(pim.getZPrinterName());
qDebug()<<"打印机DPI" <<printer.resolution();

The printing result is as follows, the printer is Zebra ZD888, 203DPI is correct

insert image description here

Next, let's calculate the actual print size of the font. It is very convenient to set the line height. You don't need to try it like a blind person.

pim是个用来存储打印机信息的类,自己写的,看变量名应该就能知道意思了,此处就不赘述了

 // 设置字体和文本颜色
    QFont font(pim.getZFont(), pim.getZFontSize().toInt());
    painter.setFont(font);
    painter.setPen(Qt::black);

    QFontMetrics fontMetrice(font);
    qDebug()<<"字体高度:"<<fontMetrice.height();
    qDebug()<<"leading:"<<fontMetrice.leading();
    qDebug()<<"lineSpace:"<<fontMetrice.lineSpacing();

    painter.drawText(0, 0, printer.width()/2-5, printer.height(), Qt::AlignTop, "配料清单");
    font=QFont(pim.getZFont(), pim.getZFontSize().toInt());
    painter.setFont(font);
    //打印机DPI* 字体高度/72,字体高度单位为磅,1磅等于1/72英寸。
    int contentLineHegiht=printer.resolution()*fontMetrice.height()/72;

おすすめ

転載: blog.csdn.net/weixin_42485732/article/details/130515995