简体   繁体   中英

How to check pushButtons with draging the mouse QT ? MouseMoveEvent

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 ?

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.

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

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);
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM