why overriding paintEvent in MainWindow doesn't work
Unsolved
General and Desktop
-
I just started learning QT. I want overriding the function paintEvent of MainWindow to draw some graphics, But it doesn't work. Thanks for your help.
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QPainterPath> #include <QPainter> #include <QPaintEvent> #include <iostream> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); protected: void paintEvent(QPaintEvent *event); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::paintEvent(QPaintEvent *event) { auto rect = event->rect(); QPainter painter(this); painter.setPen(QPen(Qt::red,5, Qt::DashDotLine, Qt::RoundCap)); QFont font; font.setPixelSize(140); painter.setFont(font); painter.drawText(rect,Qt::AlignRight, "display"); std::cout << "here" << std::endl; }
main.cpp
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.setWindowTitle("main"); w.show(); return a.exec(); }
Nothing in the main windows when I run the code.
-
Works fine for me - a big red text 'display' is drawn on the mainwindow.
-
Hi and welcome to devnet,
Since you have a ui file, any chances you have a widget set as central widget of your QMainWindow based class ?