TextEdit painting C++
-
Hi everyone,
I read many posts of how to paint on Qtextedit, but I cannot get out of the problem.I create a form with a qtextedit named text and a class named textedit. Then, I wrote paintEvent(QPaintEvent* event) method in this way:
void textedit::paintEvent(QPaintEvent* event) { QCursor cursorQ = ui->text->cursor(); QPoint point= cursorQ.pos(); QPainter p(this); p.drawText(QPoint(30,30), "|"); p.drawText(point, "|"); }
The first drawText works and draw "|" character out of the QTextEdit area in the QPoint(30, 30), the second don't and I don't understand why.
It's produced:
"QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1"
output.
Maybe it is because QPainter is reffered to the entire window and QPoint only to Qtextedit area? If this is the reason, how can I get what I want?
I read some posts where people recommend usingQPainter p(viewport());
but it produced "used of undeclared identifier viewport " error.
What can I have miss?
(I used drawtext only as example for me, for understanding how to paint in the QTextEdit area)
There .cpp and .h files:
#ifndef TEXTEDIT_H #define TEXTEDIT_H #include <QMainWindow> #include <QCursor> #include <unistd.h> #include <QTextCharFormat> #include <QTextCursor> #include <QDebug> #include <QPainter> namespace Ui { class textedit; } class textedit : public QMainWindow { Q_OBJECT public: explicit textedit(QWidget *parent = nullptr); ~textedit(); private: Ui::textedit *ui; QTextCursor cursor; protected: void paintEvent(QPaintEvent* event); }; #endif // TEXTEDIT_H
#include "textedit.h" #include "ui_textedit.h" textedit::textedit(QWidget *parent) : QMainWindow(parent), ui(new Ui::textedit) { ui->setupUi(this); ui->text->setText("Hello, World!\nAnotherLine.\n"); } textedit::~textedit() { delete ui; } void textedit::paintEvent(QPaintEvent* event) { QCursor cursorQ = ui->text->cursor(); QPoint point= cursorQ.pos(); QPainter p(this); p.drawText(QPoint(30,30), "|"); p.drawText(point, "|"); }
Thanks for any reply or advice.
-
Hi,
point
is likely local to the QTextEdit so completely unrelated to your QMainWindow. You have to translate the coordinate to make it draw where you want. -
Take a look at the various point mapping related functions.