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
Maybe you might be interested in examples which come with Qt:Search for
paintEvent
in them. -
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 yourui
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);