代码:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QList<QPushButton *> Sensor_list;
Sensor_list.append(ui->pushButton_3);
Sensor_list.append(ui->pushButton_4);
Sensor_list.append(ui->pushButton_5);
Sensor_list.append(ui->pushButton_8);
QString text;
for(int i=0;i<4;i++)
{ text=Sensor_list[i]->text();
connect(Sensor_list[i],SIGNAL(clicked()),this,SLOT(pushButton_clicked(text)));
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::pushButton_clicked(QString text)
{
qDebug()<<text;
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSqlDatabase>
#include <QMessageBox>
#include <QSqlQuery>
#include <QDebug>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void pushButton_clicked(QString text);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
运行是出现:
Object::connect: No such slot MainWindow::pushButton_clicked(text)
Object::connect: (sender name: 'pushButton_3')
Object::connect: (receiver name: 'MainWindow')
Object::connect: No such slot MainWindow::pushButton_clicked(text)
Object::connect: (sender name: 'pushButton_4')
Object::connect: (receiver name: 'MainWindow')
Object::connect: No such slot MainWindow::pushButton_clicked(text)
Object::connect: (sender name: 'pushButton_5')
Object::connect: (receiver name: 'MainWindow')
Object::connect: No such slot MainWindow::pushButton_clicked(text)
Object::connect: (sender name: 'pushButton_8')
Object::connect: (receiver name: 'MainWindow')
这是为何???我明明有MainWindow::pushButton_clicked(text)?
------解决方案--------------------
connect(Sensor_list[i],SIGNAL(clicked()),this,SLOT(pushButton_clicked(text)))这句怎么能带参数呢,后面的SLOT应该是参数的类型啊,connect(Sensor_list[i],SIGNAL(clicked()),this,SLOT(pushButton_clicked(QString)));
并且signal和slot参数不匹配啊,这也是个问题啊
------解决方案--------------------
connect(Sensor_list[i],SIGNAL(clicked()),this,SLOT(pushButton_clicked(text)));
signal的接口为“clicked()" 是个无参数的signal
而SLOT为puhsButton_clicked(QString)是一个有参数的,参数为QString
connect接口只传递参数类型,不传递参数名
所以正确的方式应该为
connect(Sensor_list[i],SIGNAL(clicked()),this,SLOT(pushButton_clicked()));
你可以在pushButton_clicked里再去根据Sensor_list[i]对象获取当前值
------解决方案--------------------
slot时声明为
void pushButton_clicked(QString text);
则进行connect绑定时语法为
QObject::connect(xx,SIGNAL(),XXX,SLOT(pushButton_clicked(QString)));
注意后面跟的是类型,而不是变量名,编译器只关心变量的类型,不关心变量名
但你signal和slot类型不匹配,里面的参数一个是QString类型,一个是无参数的,你如何期望对于你这种自定义的行为,编译器或qt框架能给你传递正确的值呢?
------解决方案--------------------
我前面已经说了
你要么在pushButton_click里自己去处理
要么另外封装一个slot,当触发clicked()事件时,在这个自己定义的slot里去封装你需要的参数,然后再次发送signal
类似如下
void MainWindow::signal_btn_clicked()
{
int index = ...;
QString txt = ...;
emit myDefineSignal(index,txt);
}