Qtでテキストボックスの内容(QTextDocument)をキャンバスに描画するには?

以下のコードはQTextEditをそのまま自身のキャンバスに描画するクラスの一例です。 自由に切り貼りして、自分にあった形に直してください。 class TextCanvas : public QWidget { Q_OBJECT public: explicit TextCanvas(QWidget *parent = nullptr) : QWidget(parent) {} void setTextEdit(QTextEdit *edit) { textEdit = edit; update(); } void setDrawRect(const QRectF &rect) { drawRect = rect; update(); } protected: void paintEvent(QPaintEvent *) override { if (!textEdit) return; QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); QTextDocument *doc = textEdit->document(); // 横幅を指定 doc->setTextWidth(drawRect.width()); painter.save(); // ① 描画開始位置 painter.translate(drawRect.topLeft()); // ② 縦横制限 painter.setClipRect(QRectF(0, 0, drawRect.width(), drawRect.height())); // ③ 描画 doc->drawContents(&painter); painter.restore(); } private: QTextEdit *textEdit = nullptr; QRectF drawRect = QRectF(0, 0, 300, 200); // デフォルト };

2026年1月29日