8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PySideで印刷した

Posted at

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)
8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?