Search code examples
c++qtmouseeventqpainter

Declaring functions called when a mouse event ocurr in Qt


I'm a beginner in Qt when I run the following code I got these errors:

  • no void MainWindow::mousePressEvent(QMouseEvent *f) member function declared in class 'mainwindow'.
  • no void void MainWindow::paintEvent(QPaintEvent *e) member function declared in class 'mainwindow'.

The code is written in main.cpp file and I didn't write anything in mainwindow.cpp or mainwindow.h The Qt code:

#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QEvent>
#include <QMouseEvent>
#include <QPainter>
void MainWindow::mousePressEvent(QMouseEvent *f)
{
    QPoint point=f->pos();
    int y=1;
    update();
}
void MainWindow::paintEvent(QPaintEvent *e)
{
    int y;
    QPoint point;
    QPainter painter(this);
    QPen linepen(Qt::red);
    linepen.setCapStyle(Qt::RoundCap);
    linepen.setWidth(30);
    painter.setRenderHint(QPainter::Antialiasing,true);
    painter.setPen(linepen);
    if(y==1)
        painter.drawPoint(point);

}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;

w.show();
return a.exec();
}

Solution

  • In header should be:

    protected:
    
    void mousePressEvent(QMouseEvent *f);
    void paintEvent(QPaintEvent *e);
    

    And includes:

    #include <QMouseEvent>
    #include <QPaintEvent>
    

    Also you should write your code in mainwindow.cpp(paintEvent, and another member functions). If you will have many classes, then your main.cpp can be very hard-readable.