Ok so i have created my UI with the drag and drop part of Qt and in the Ui i created a "Tab Widget" inside another "Tab Widget". Now, inside the second Tab Widget i created a Frame
My Question is, how do i draw on top of this frame in Qt?
i tried this but no luck at all. Ive tried different ways on going about this, the program runs good but when i go and see if the frame was drawn on, i see nothing...please help me with this, with code example and all. Thanks in advance.
void 2ndMainWindow::paintEvent(QPaintEvent *e)
{
QPainter paint(ui->rightTriangle_frame);
paint.drawEllipse(10,10,100,100);
paint.setPen(Qt::red);
paint.end();
}
my header file included this under the private slot
Ui::GeometryMainWindow *ui;
QGraphicsScene *scene;
QGraphicsEllipseItem *ellipse;
QGraphicsRectItem *rectangle;
ui->setupUi(this);
scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
QBrush redBrush(Qt::red);
QBrush blueBrush(Qt::blue);
QPen blackpen(Qt::black);
blackpen.setWidth(6);
ellipse = scene->addEllipse(10,10,100,100,blackpen,redBrush);
If you are going to draw some customized shapes on QFrame, I suggest you to use a QGraphicsView instead of QFrame. Implementing the paintEvent of a widget may create performance issues. If you use a QGraphicsView, you can create a QGraphicsScene and add your items to that scene which is the general and accepted way of doing this kind of stuff.
Alternatively, implement an eventFilter as below,
bool 2ndMainWindow::eventFilter(QObject *o, QEvent *e)
{
if (e->type() == QEvent::Paint) {
paintEvent((QPaintEvent *)e);
}
return QMainWindow::eventFilter(o, e);
}
In constructor of your mainwindow add,
installEventFilter(this);
By the way, you should set your pen before drawing your ellipse in paintEvent function.
It seems that you are overriding the paintEvent()
method of your main window and from there trying to paint on the frame widget. Look at your console output - you should get a message like
QPainter::begin: Widget painting can only begin as a result of a paintEvent
QPainter::setPen: Painter not active
QPainter::end: Painter not active, aborted
Instead, subclass your QFrame
widget (in Qt designer, select "Promote to ..." to define the user defined subclass) and in this subclass, override paintEvent
like this:
void MyFrame::paintEvent(QPaintEvent *e) {
QPainter paint(this);
paint.setPen(Qt::red);
paint.drawEllipse(10,10,100,100);
paint.end();
QFrame::paintEvent(e);
}
Note that, in order to draw a red ellipse, you need to set the pen color before drawing the ellipse, of course. You should also call the paintEvent()
method of the parent class in order to draw the frame border.
See https://github.com/afester/StackOverflow/tree/master/QtRepaint for an SSCCE.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.