qt how to know that a pushbutton is clicked?

让人想犯罪 __ 提交于 2019-12-04 16:36:23

For example by connecting the clicked signal from all the buttons to a slot, and then use QObject::sender() to find out which button it was.

Let's assume your buttons are named pushButton, pushButton_2 and pushButton_3 and labels label, label_2 and label_3 respectively.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(play()));
    connect(ui->pushButton_2, SIGNAL(clicked()), this, SLOT(play()));
    connect(ui->pushButton_3, SIGNAL(clicked()), this, SLOT(play()));
}

void MainWindow::play()
{
    QString piece;
    QObject* button = QObject::sender();
    if (button == ui->pushButton)
    {
        piece = ui->label->text();
    }
    else if (button == ui->pushButton_2)
    {
        piece = ui->label_2->text();
    }
    else
    {
        piece = ui->label_3->text();
    }

    qDebug() << "Starting to play:" << piece;
}

You can also assign the three buttons to a QButtonGroup and use its signal void QButtonGroup::buttonClicked(int id), which gives you the id of a pushbutton which was clicked. Just make sure to set the IDs of each button beforehand(for instance in the constructor or some init function). By doing so, you don't have to deal with pointers.

https://doc.qt.io/archives/qt-4.8/qbuttongroup.html#buttonClicked-2 https://doc.qt.io/archives/qt-4.8/qbuttongroup.html#setId

In modern code, you should use the Qt 5's connect syntax and simply connect to a functor when your action is trivial, like yours is:

// Interface
#include "ui_MainWindow.h"

class MainWindow : public QMainWindow {
  Q_OBJECT
  Ui::MainWindow ui;
  QVector<QString> m_pieces;
  ...
public:
  explicit MainWindow(QWidget *parent = nullptr);
  void play(const QString &piece);
};

// Implementation
MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent)
{
  ui.setupUi(this);
  unsigned i = 0;
  for(auto *button :
        {&ui.pushButton_1, &ui.pushButton_2, &ui.pushButton_3}) {
    connect(button, &QPushButton::clicked, [this, i]{
      if (m_pieces.size() > i) play(m_pieces[i]);
    });
    i ++;
  }
}

void MainWindow::play(const QString & piece) {
  ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!