Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Draw a point when button is clicked



  • So, I created 2 functions: onClick() - function that executes when the button is clicked, and drawPoint(int x,int y).
    onClick function calls the drawPoint function with x and y parameters, but when I run the program, and I click the button, it says:
    "QPainter::drawPoints: Painter not active".
    Here's my mainwindow.cpp:

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        QPushButton *button = QMainWindow::findChild<QPushButton *>("pushButton");
        connect(button, SIGNAL(released()), SLOT(onClick()));
    
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    
    void MainWindow::drawPoint(int x, int y) {
    
        QPainter painter;
        painter.drawPoint(x,y);
    
    }
    
    void MainWindow::onClick() {
        QPoint point = QCursor::pos();
        int x = point.x();
        int y = point.y();
        drawPoint(x,y);
    }
    
    

    I'm a total beginner in Qt, and have no idea what's going on. I've searched on this forum, but I couldn't find anything.



  • @mitrovicl
    You can only draw a point in a paint event.

    Basically, can you pick something different from this to do? Widget applications are not usually about drawing points. Depends what you are ultimately trying to achieve.



  • @JonB Thanks for the answer, I'm trying to create CPS (Clicks per second) test. And I want every click to leave a "trail". I'll look into pain events.



  • @mitrovicl
    Maybe you might be interested in examples which come with Qt:

    Basic Drawing Example

    Scribble Example

    Search for paintEvent in them.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    The first thing: you cannot paint on a widget outside the paint event.

    Second, please read the QPainter documentation. It provides a lot of information as well as links to various examples.



  • @mitrovicl said in Draw a point when button is clicked:

    QPushButton *button = QMainWindow::findChild<QPushButton *>("pushButton");

    I assume you have a mainWindow.ui (modified with QtDesigner), then this is not necessary.
    Just access you button by using your ui pointer.

    ui->pushButton
    

    connect(button, SIGNAL(released()), SLOT(onClick()));

    and better use the updated, Qt5 function-based "Signal & Slot"-syntax.

    connect(ui->pushButton, &QPushButton::released, this, &MainWindow::onClick);
    

Log in to reply