PDA

View Full Version : QRubberBand in child widgets



davethomaspilot
23rd September 2021, 21:33
I can get QRubberBand to work when I provide mouseEvent overrides in my MainWindow widget. But, I want to get rectangle coordinates relative to a child widget's origin.

Seems like this would be easier than getting the offset and scaling between the MainWindow?

The centralWidget of the MainWindow is contained in another widget (ImageComposer->window). I tried implementing the mouse event overrides in the ImageComposer class, but the code doesn't execute:


void ImageComposer::mousePressEvent(QMouseEvent *event)
{
//doingRB = false;
origin = event->pos();
//if (!rubberBand)
rubberBand = new QRubberBand(QRubberBand::Rectangle, window);
rubberBand->setGeometry(QRect(origin, QSize()));
rubberBand->show();
}

void ImageComposer::mouseMoveEvent(QMouseEvent *event)
{

//doingRB = true;
rubberBand->setGeometry(QRect(origin, event->pos()).normalized());
}

The same code runs as expected when located in MainWindow.

Do I need to subclass a QWidget and implement the mouseEvent overrides in that new class? Then, instantiate the class with mouseEvent methods instead of an ordinary QWidget?

Does this seem better than getting the rectangle coordinates in the mainWindow coordinate system then converting?

Thanks!

Added after 8 minutes:

Subclassing a QWidget and implementing the mouseEvent methods in that class works.

Is this the better way of getting the coordinates relative to the child widget's origin?