QRubberBand
-
I wrote this code to paint a rectangle when I press and move the mouse but it doesn't work...I don't understand why..can you help me?
void Widget::mousePressEvent(QMouseEvent *event)
{
origin = event->pos();
if (!rubberBand)
rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
rubberBand->setGeometry(QRect(origin, QSize()));
rubberBand->show();
}void Widget::mouseMoveEvent(QMouseEvent *event)
{
rubberBand->setGeometry(QRect(origin, event->pos()).normalized());
}void Widget::mouseReleaseEvent(QMouseEvent *event)
{
rubberBand->hide();
// determine selection, for example using QRect::intersects()
// and QRect::contains().
} -
@vale88 said in QRubberBand:
but it doesn't work
what happens instead?
Are you sure the mouseMoveEvent() event handler is called? -
@raven-worx nothing happends ..I don't understand..I move the mouse but nothing happends
-
Hi,
That might sound silly but are you first pressing one of the mouse button ?
To ensure that your methods are called you can put
qDebug
statements in each of them. -
@vale88 said in QRubberBand:
@SGaist event are void function...yes,I pres the button of the mouse
What do you mean by
event are void function
? And were is it related to my suggestion of puttingqDebug
statements in these functions to check what is happening ? -
Events work with qDebug().
But when insert code of rectangular, it doesn't work.
There is a crash in the application. -
Thisi is my code .cpp :
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRubberBand>
#include <QMouseEvent>MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}MainWindow::~MainWindow()
{
delete ui;
}void MainWindow::mousePressEvent(QMouseEvent * event)
{
origin = event->pos(); if (!rubberBand) rubberBand = new QRubberBand(QRubberBand::Rectangle, this); rubberBand->setGeometry(QRect(origin, QSize(20,10))); rubberBand->show();
ui->textBrowser->append("press");
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
rubberBand->setGeometry(QRect(origin, event->pos()).normalized());
ui->textBrowser->append("release");
}void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
rubberBand->hide();
ui->textBrowser->append("move");
}And .h :
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QRubberBand>namespace Ui {
class MainWindow;
}class MainWindow : public QMainWindow
{
Q_OBJECTpublic:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
void mousePressEvent(QMouseEvent * event);
void mouseMoveEvent(QMouseEvent * event);
void mouseReleaseEvent(QMouseEvent * event);private:
Ui::MainWindow *ui;
QPoint origin;
QRubberBand *rubberBand;
};#endif // MAINWINDOW_H
I don't know if something there isn't.
-
You forgot to initialise your QRubberBand variable to nullptr in the constructor.