qt信号槽特殊使用方式

 connect 函数的第四个参数可传递信号,作为连接源。代码如下:

// View.h

class View : public QWidget {
    Q_OBJECT

public:
    explicit View(QWidget *parent = nullptr);

signals:
    void buttonClicked();

private:
    QPushButton *button;
};
// View.cpp

View::View(QWidget *parent) : QWidget(parent) {
    button = new QPushButton("Click me", this);
    connect(button, &QPushButton::clicked, this, &View::buttonClicked);
}
// Presenter.h

class Presenter : public QObject {
    Q_OBJECT

public:
    explicit Presenter(View *view);

private slots:
    void handleButtonClicked();

private:
    View *view;
};
// Presenter.cpp

Presenter::Presenter(View *view) : QObject(nullptr), view(view) {
    connect(view, &View::buttonClicked, this, &Presenter::handleButtonClicked);
}

void Presenter::handleButtonClicked() {
    // 处理按钮点击事件的逻辑
}

在上面的示例中,View 类中定义了一个名为 buttonClicked 的信号,并在构造函数中将按钮的 clicked 信号连接到这个信号。Presenter 类中通过连接 View 的信号 buttonClicked 到自己的槽函数 handleButtonClicked 来处理按钮点击事件。

通过这种方式,View 和 Presenter 可以实现解耦,各自专注于自己的职责。View 负责用户界面的展示和用户交互,Presenter 负责处理业务逻辑。信号槽机制使得二者之间的通信变得简单和灵活。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值