当你觉得写代码是一件重复性极高的工作时,这时你就应该考虑换个方式来实现了。
提高代码效率,减少代码量。
代码片:
- void Widget::onClicked()
- {
- QPushButton* button = qobject_cast<QPushButton*>(sender());
- QRadioButton* radio = qobject_cast<QRadioButton*>(sender());
- if (button)
- {
- QString text = button->text();
- ui->label_2->setText(text);
- }
- else if(radio)
- {
- QString text = radio->text();
- ui->label_2->setText(text);
- }
- }
实例:
1、在Qt creator中拖拽出如下界面:
2、添加槽函数。
- private slots:
- void onClicked();
3、添加信号与槽的关联。
- connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(onClicked()));
- connect(ui->pushButton_2,SIGNAL(clicked(bool)),this,SLOT(onClicked()));
- connect(ui->pushButton_3,SIGNAL(clicked(bool)),this,SLOT(onClicked()));
- connect(ui->pushButton_4,SIGNAL(clicked(bool)),this,SLOT(onClicked()));
- connect(ui->radioButton,SIGNAL(clicked(bool)),SLOT(onClicked()));
- connect(ui->radioButton_2,SIGNAL(clicked(bool)),SLOT(onClicked()));
- connect(ui->radioButton_3,SIGNAL(clicked(bool)),SLOT(onClicked()));
- connect(ui->radioButton_4,SIGNAL(clicked(bool)),SLOT(onClicked()));
4、实现槽函数。
- void Widget::onClicked()
- {
- QPushButton* button = qobject_cast<QPushButton*>(sender());
- QRadioButton* radio = qobject_cast<QRadioButton*>(sender());
- if (button)
- {
- QString text = button->text();
- ui->label_2->setText(text);
- }
- else if(radio)
- {
- QString text = radio->text();
- ui->label_2->setText(text);
- }
- }
5、运行截图:
当然了,这里我只是举个例子,在实际的应用中大家可以扩展其功能的。
http://blog.csdn.net/rl529014/article/details/52144009