折腾了一天终于搞定了!!!
终于对信号和槽有点了解了。
先贴一下代码吧:
代码: 全选
//employee.h
#include <QtCore>
#include <QApplication>
#include <iostream>
#include <QWidget>
using namespace std;
class Employee:public QObject
{
Q_OBJECT
public:
Employee();
int getValue()
{
return value;
}
void peek(); //peek the private value
void changeValue(int); //changeValue by manual and then ruslt in emiting a signal
public slots: //if valueChanged then setValue
void setValue(int);
signals:
void valueChanged(int);
private:
int value;
};
代码: 全选
//employee.cpp
#include "employee.h"
Employee::Employee()
{
value = 0;
cout<<"the initial value is 0"<<endl;
QObject::connect(this,SIGNAL(valueChanged(int)),this,SLOT(setValue(int)));
}
void Employee::changeValue(int num)
{
if(value != num)
{
emit valueChanged(num);
}
}
void Employee::setValue(int newValue)
{
value = newValue;
}
void Employee::peek()
{
cout<<"The value you have peeked is "<<value<<endl;
}
代码: 全选
//main.cpp
#include "employee.h"
#include <QApplication>
int main (int argc, char * argv[])
{
QApplication app(argc, argv);
cout<<"begin"<<endl;
Employee em;
cout<<em.getValue()<<endl;
em.changeValue(6);
cout<<em.getValue()<<endl;
cout<<"end"<<endl;
return app.exec();
}
注意:
1.这三个文件
不能合成一个文件,否则会出现一大堆“Undefine reference to XX ”之类的错误。我在这儿试过N次,也在这儿栽过N次
,这儿给自己提个醒,也希望能引起大家的注意
。
至于原因我想因为编译时,要用moc工具对信号和槽的filename.h头文件中的宏进行处理,生成moc_filename.cpp文件,如果搞到一块的话moc就找不到filename.h文件了,就算找到了也会搞的一团糟。所以还是分开写比较好,既便于管理,又美观,还省去了不少烦人的错误。。。
2.如果要用Qt里的信号和槽机制的话,该类一定要继承QOject类,或是其子类,而且必须加上Q_OBJECT宏。原话是这么说的
“All classes that contain signals or slots must mention Q_OBJECT at the top of their declaration. They must also derive (directly or indirectly) from QObject.”
3.在命令行下的话别忘了及时更新Makefile文件。否则会原地踏步,浪费时间和精力
。某些IDE可以自动更新,如果遇到错误又总是发现不了的话,可以到命令行下手动更新。。。