signal和slot的简单使用不知道错误在哪里?
我试着用signal/slot连接两个类(in1和out2)。in1中产生数据发送信号,out1中接受信号,并输出。编译没错,只是out1中一直没有输出。貌似发送的信号和槽函数没有连接起来。。不明白 。。。
[code=C/C++][/code]#include <QObject>
class in1 : public QObject
{
Q_OBJECT
public:
explicit in1(QObject *parent = 0);
int i;
signals:
void vaidchange(int);
public slots:
};
using std::cin;
in1::in1(QObject *parent) :
QObject(parent)
{
std::cout<<"hello";
for(int i=0;i<10;i++)
{
std::cout<<i<<std::endl;
emit vaidchange(10);
}
}
class out1 : public QObject
{
Q_OBJECT
public:
explicit out1(QObject *parent = 0);
signals:
public slots:
void getvaild(int);
};
out1::out1(QObject *parent) :
QObject(parent)
{
}
void out1::getvaild(int iou)
{
int iu;
iu=iou+10;
std::cout<<"i="<<iu;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
in1 in1;
out1 out1;
QObject::connect(&in1,SIGNAL(vaidchange(int)),&out1,SLOT(getvaild(int)));
return a.exec();
}
结果显示只有in1的输出 out1没输出。。。
[解决办法]
in1::in1(QObject *parent) :
QObject(parent)
{
std::cout<<"hello";
for(int i=0;i<10;i++)
{
std::cout<<i<<std::endl;
emit vaidchange(10);
}
}
你在构造中就发送了信号,构造的时候你的 QObject::connect(&in1,SIGNAL(vaidchange(int)),&out1,SLOT(getvaild(int)));连接的这句话多还没执行,当然接收不到。