DEV Community

海前 王
海前 王

Posted on • Edited on

singal and slot

mainwindow.h &cpp
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QWidget>
#include <QDebug>
#include"qperson.h"
class MainWindow : public QWidget
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
  QPerson *person ;
private slots:
    void handleButtonClicked();
    void onAgeChanged(int newAge)
        {
            qDebug() << "Age changed to:" << newAge;
        }
};

#endif // MAINWINDOW_H
#include "mainwindow.h"
#include <QPushButton>
#include <QVBoxLayout>
#include <QDebug>
#include<QSpinBox>
#include<QTableWidget>

#include "QPerson.h"
MainWindow::MainWindow(QWidget *parent) : QWidget(parent)
{
    QSpinBox *spinBox = new QSpinBox(this);
    QPushButton *button = new QPushButton("Print SpinBox Value", this);

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(spinBox);
    layout->addWidget(button);

  person = new QPerson;


        person->incAge();


           connect(person, &QPerson::ageChanged, this, &MainWindow::onAgeChanged);
           person->incAge();
    connect(button, &QPushButton::clicked, this, &MainWindow::handleButtonClicked);

    //QTableWidget *tab=new QTableWidget(this);



}

void MainWindow::handleButtonClicked()
{
       person->incAge();
    QSpinBox *spinBox = qobject_cast<QSpinBox *>(sender());
    if (spinBox) {
        qDebug() << "SpinBox value:" << spinBox->value();
    } else {
        qDebug() << "Sender is not a QSpinBox";
    }
}
Enter fullscreen mode Exit fullscreen mode
qperson h &cpp

#ifndef QPERSON_H
#define QPERSON_H

#include <QObject>

class QPerson : public QObject
{
    Q_OBJECT
public:
    explicit QPerson(QObject *parent = nullptr);

    void incAge(); // 增加年龄


signals:
    void ageChanged(int newAge); // 声明信号

private:
    int m_age;
};

#endif // QPERSON_H


#include "qperson.h"

QPerson::QPerson(QObject *parent) : QObject(parent)
{

}
void QPerson::incAge()
{
    m_age++;
    emit ageChanged(m_age); // 发射信号
}

Enter fullscreen mode Exit fullscreen mode
main
#include <QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow window;
    window.show();
    return app.exec();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)