Reputation: 83
I have 5 pushButtons ( pushButton_i ) i = 1, 2, 3, 4, 5. What I want to do is to drag the mouse ( button pressed ) and then setText of checked buttons on "Yes", otherwise on "NO". I tried the following code but the result is : When I press the mouse Button and then move it a little bit, all buttons' texts are set on "NO". This is my code :
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include<QEvent>
#include <QMouseEvent>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
QString key;
for (int i=1;i<=5;i++){
key = QString("pushButton_%1").arg(i);
QPushButton *button = ui->centralwidget->findChild<QPushButton*>(key);
QRect widgetRect = button->geometry();
widgetRect.moveTopLeft(button->parentWidget()->mapToGlobal(widgetRect.topLeft()));
if (button->rect().contains(event->pos())) button->setText("Yes");
else button->setText("No");
}
}
Can someone please explain to me what is going on ?
Upvotes: 0
Views: 268
Reputation: 83
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
QString key;
for (int i = 1; i <= 5; i++)
{
key = QString("pushButton_%1").arg(i);
QPushButton *button = ui->centralwidget->findChild<QPushButton*>(key);
button->setCheckable(true);
}
QWidget* child = ui->centralwidget->childAt(event->pos());
QPushButton* affectedBtn = dynamic_cast<QPushButton*>(child);
if (affectedBtn)
affectedBtn->setChecked(true);
}
Upvotes: 0
Reputation: 56
Try it with this:
void ButtonDrag::mouseMoveEvent(QMouseEvent *event)
{
QString key;
for (int i = 1; i <= 5; i++)
{
key = QString("pushButton_%1").arg(i);
QPushButton *button = ui.centralWidget->findChild<QPushButton*>(key);
button->setText("No");
}
QWidget* child = ui.centralWidget->childAt(event->pos());
QPushButton* affectedBtn = dynamic_cast<QPushButton*>(child);
if (affectedBtn)
affectedBtn->setText("Yes");
}
Problem is, that i don't know how to do it without a downcast. But at least it works xD. I set the text of all buttons to "No" and get the affectedBtn (if there's one) by ui.centralWidget->childAt(event->pos()), which i have to downcast to use the setText method
Upvotes: 0
Reputation: 1330
From the documentation:
QMouseEvent::pos()
reports the position of the mouse cursor, relative to this widget
However, you change the position of the button by making it at point (0, 0). I don't know why you relocate the button.
Upvotes: 0