void ArialPrintTest::printSlot() { // 创建打印机对象 QPrinter printer(QPrinter::ScreenResolution); // 创建打印对话框 QString printerName = printer.printerName(); if (printerName.size() == 0) return; QPrintDialog dlg(&printer, this); // 如果在对话框中按下了打印按钮,则执行打印操作 if (dlg.exec() == QDialog::Accepted) { QPainter painter; bool bOk = painter.begin(&printer); if (bOk) { paintText(&painter); } } } void ArialPrintTest::paintText(QPainter *painter) { QFont font; font.setPointSize(8); font.setFamily("Arial"); font.setKerning(false); QTextOption textOption; textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); textOption.setAlignment(Qt::AlignJustify); QString strText = "Element A QTextDocument can be used ,to present formatted text A QTextDocument can be used to present formatted text"; QTextLayout *pTextLayout = new QTextLayout(); pTextLayout->setText(strText); pTextLayout->setTextOption(textOption); pTextLayout->setFont(font); double height = 0; int lineWidth = 348; int lineSpacing = 1; if (!pTextLayout->text().isEmpty()) { pTextLayout->beginLayout(); while (true) { QTextLine line = pTextLayout->createLine(); if (!line.isValid()) break; line.setLineWidth(lineWidth); line.setPosition(QPointF(0, height)); height += line.height(); height += lineSpacing; } pTextLayout->endLayout(); } QRect textRect(50, 50, 348, 75); pTextLayout->draw(painter, textRect.topLeft(), QVector(), textRect); painter->end(); }