- QPushButton::clicked是一个信号,当按钮被用户点击时发出。它可以携带一个布尔值参数,表示是否按钮被按下
- QPushButton::click是一个槽,当调用它时,会模拟按钮被点击的效果,并发出clicked信号
两个示例帮助理解
- 一个示例,演示了如何将两个按钮的clicked信号连接到同一个槽函数,并根据参数判断哪个按钮被点击
| |
| #ifndef MAINWINDOW_H |
| #define MAINWINDOW_H |
| |
| #include <QMainWindow> |
| #include <QPushButton> |
| #include <QLabel> |
| |
| class MainWindow : public QMainWindow |
| { |
| Q_OBJECT |
| |
| public: |
| MainWindow(QWidget *parent = nullptr); |
| ~MainWindow(); |
| |
| private: |
| QPushButton *button1; |
| QPushButton *button2; |
| QLabel *label; |
| |
| private slots: |
| void onButtonClicked(bool checked); |
| }; |
| #endif |
| |
| |
| #include "mainwindow.h" |
| |
| MainWindow::MainWindow(QWidget *parent) |
| : QMainWindow(parent) |
| { |
| button1 = new QPushButton(this); |
| button2 = new QPushButton(this); |
| label = new QLabel(this); |
| |
| button1->setText("Button 1"); |
| button2->setText("Button 2"); |
| label->setText("No button clicked"); |
| |
| button1->setGeometry(100, 100, 100, 50); |
| button2->setGeometry(300, 100, 100, 50); |
| label->setGeometry(200, 200, 150, 50); |
| |
| connect(button1,SIGNAL(clicked(bool)),this,SLOT(onButtonClicked(bool))); |
| connect(button2,SIGNAL(clicked(bool)),this,SLOT(onButtonClicked(bool))); |
| } |
| |
| void MainWindow::onButtonClicked(bool checked) |
| { |
| if(sender() == button1) |
| { |
| label->setText("Button 1 clicked"); |
| } |
| else if(sender() == button2) |
| { |
| label->setText("Button 2 clicked"); |
| } |
| } |
| |
| MainWindow::~MainWindow() |
| { |
| } |
- 另一个示例,演示了如何在自定义的槽函数中使用QPushButton::click来模拟按钮被点击,并弹出对话框
| |
| #ifndef MAINWINDOW_H |
| #define MAINWINDOW_H |
| |
| #include <QMainWindow> |
| #include <QPushButton> |
| #include <QMessageBox> |
| |
| class MainWindow : public QMainWindow |
| { |
| Q_OBJECT |
| |
| public: |
| MainWindow(QWidget *parent = nullptr); |
| ~MainWindow(); |
| |
| private: |
| QPushButton* button; |
| |
| private slots: |
| void on_button_clicked(); |
| }; |
| #endif |
| |
| |
| #include "mainwindow.h" |
| |
| MainWindow::MainWindow(QWidget *parent) |
| : QMainWindow(parent) |
| { |
| button = new QPushButton(this); |
| button->setText("Click Me"); |
| button->setGeometry(200,200,80,40); |
| |
| connect(button,SIGNAL(clicked()),this,SLOT(on_button_clicked())); |
| } |
| |
| void MainWindow::on_button_clicked() |
| { |
| button->click(); |
| QMessageBox::information(this,"Message","You clicked the button!"); |
| } |
| |
| MainWindow::~MainWindow() |
| { |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧