Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
5
Help us understand the problem. What are the problem?

posted at

PySideで印刷した

Pythonで、帳票を印刷するアプリ書こうと思って、どうやったら印刷出来るんだろうと色々ググってみたけど、結局Qt使う事にして、それならPySideで印刷する方法を調べてたけど、しっくりするサンプルが無かったので、作ってみた。

とりあえず、QPrinterオブジェクト作っておいて、QPrintDialogでユーザーにプリンターを選択させて、設定されたQPrinterオブジェクトをQPainterオブジェクトに渡して、QPainterオブジェクトで描画するという手順だった

import sys
from PySide6.QtWidgets import QApplication
from PySide6.QtPrintSupport import QPrintDialog, QPrinter
from PySide6.QtGui import QImage, QPainter


def print_dialog(printer_obj):
    dialog = QPrintDialog(printer_obj, None)
    dialog.setWindowTitle("Print Document")
    return dialog


def print_image(printer_obj):
    painter = QPainter(printer_obj)
    # draw_squares(painter)

    draw_text(painter)
    draw_squares(painter)


def draw_text(painter):
    font = painter.font()
    font.setPixelSize(48)

    painter.setFont(font)
    painter.drawText(100, 100, "TEST:あいうえお")


def draw_squares(painter):
    # 横線を引く
    for i in range(0, 10):
        painter.drawLine(0, i * 10, 100, i * 10)

    # 縦を引く
    for i in range(0, 10):
        painter.drawLine(i * 10, 0, i * 10, 100)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    printer = QPrinter()
    dialog = print_dialog(printer)
    if dialog.exec():
        print_image(printer)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
5
Help us understand the problem. What are the problem?