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日

Qt6のテキストカーソル移動のイベントは?

QTextEdit / QPlainTextEdit connect(textEdit, &QTextEdit::cursorPositionChanged, this, [](){ qDebug() << "カーソルが移動しました"; }); QLineEdit connect(lineEdit, &QLineEdit::cursorPositionChanged, this, [](int oldPos, int newPos){ qDebug() << oldPos << "->" << newPos; });

2026年1月29日

QtのQTextEditで選択中のテキストの色やフォントを変更するには?

A. テキストの色を変更 QTextCursor cursor = ui->textEdit->textCursor(); if (cursor.hasSelection()) { QTextCharFormat fmt; fmt.setForeground(Qt::red); // 文字色 cursor.mergeCharFormat(fmt); } B. フォントを変更 QTextCharFormat fmt; fmt.setFontFamily("Consolas"); fmt.setFontPointSize(14); fmt.setFontWeight(QFont::Bold); fmt.setFontItalic(true); cursor.mergeCharFormat(fmt);

2026年1月25日