qobject_cast(sender())用法

时间:2024-02-21 07:46:02

qobject_cast<QPushButton *>(sender())


1、当QPushButton发出一个信号时就记录发出这个信号的对象,sender获取发出信号的对象;

2、当有多个OBject发出信号时可根据sender()函数判断是哪个对象发出的;

eg:

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked (void)
{
    QPushButton *clickedButton = qobject_cast<QPushButton *>(sender());
    int digitValue = clickedButton->text().toInt();
    //ui->lineEdit->setText(ui->lineEdit->text() + QString::number(digitValue));
    ui->lineEdit->setText(ui->lineEdit->text() + QString::number(digitValue));
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
    
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    
private:
    Ui::MainWindow *ui;
private slots:
    void on_pushButton_clicked(void);
};

#endif // MAINWINDOW_H

运行的现象:


点击一次

点击两次