我刚刚开始使用Qt SIGNALS和SLOTS,我在gui示例和类中都很成功。现在,我希望将子类中的SIGNAL与兄弟类中的SLOT连接,并在父主目录中定义Connect。最终,我的目标是在处理QTcpSocket的类中接收iamges,并将数据作为char *发出,以便由另一个类处理(保存或显示)。
目前我刚刚在Console应用程序中创建了最基本的安排版本作为学习练习。我有一个寄件人班......
sender.h
#ifndef SENDER_H
#define SENDER_H
#include <QObject>
class sender : public QObject
{
Q_OBJECT
public:
sender(QObject *parent = 0);
~sender();
signals:
void output(int data);
public slots:
void test(int data);
private:
};
#endif // SENDER_H
sender.cpp
#include <iostream>
#include "sender.h"
sender::sender(QObject *parent)
: QObject(parent)
{
std::cout << "Created sender" << std::endl;
int stuff = 47;
std::cout << "stuff = " << stuff << std::endl;
connect(this, SIGNAL(output(int)), this, SLOT(test(int)));
emit output(stuff);
}
void sender::test(int data)
{
std::cout << "Got to test, data = " << data << std::endl;
}
sender::~sender()
{
std::cout << "Destroying sender" << std::endl;
}
......和接收器类......
receiver.h
#ifndef RECEIVER_H
#define RECEIVER_H
#include <QObject>
class receiver : public QObject
{
Q_OBJECT
public:
receiver(QObject *parent = 0);
~receiver();
public slots:
void input (int data);
private:
};
#endif // RECEIVER_H
receiver.cpp
#include <iostream>
#include "receiver.h"
receiver::receiver(QObject *parent)
: QObject(parent)
{
std::cout << "Created receiver" << std::endl;
}
void receiver::input(int data)
{
std::cout << "Got data as = " << data << std::endl;
}
receiver::~receiver()
{
std::cout << "Destroying receiver" << std::endl;
}
我的主要看起来像这样......
的main.cpp
#include <QtCore/QCoreApplication>
#include <iostream>
#include "sender.h"
#include "receiver.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
receiver myReceiver;
sender mySender;
if (QObject::connect(&mySender, SIGNAL(output(int)),
&myReceiver, SLOT(input(int))))
{
std::cout << "Got here so connect returned true" << std::endl;
}
return a.exec();
}
我添加了cout输出和sender :: test函数,试图弄清楚发生了什么。
对我来说,这个编译干净,运行时没有任何警告或错误但是当sender :: test SLOT被调用时,receiver :: input SLOT没有。对main in connect的测试返回true,发送者或接收者都不会过早被破坏。控制台输出是......
Created receiver
Created sender
stuff = 47
Got to test, data = 47
Got here so connect returned true
因此发出SIGNAL,SIGNAL和SLOT参数匹配,我在sender.h和receiver.h中都有Q_OBJECT宏,并且都继承自#include QObject。
怎么了?
P.S。我正在运行4.8.3,IDE是带有Qt插件的VS2010。
答案 0 :(得分:0)
答案很简单:你发送信号之前你已经将它连接到接收器而之后你已将它连接到它自己。所以你的输出绝对正确。
答案 1 :(得分:0)
在所有内容都已连接后,所有内容仅发出。这里发送者的实例化发生在发送者和接收者连接之前,这就是发射完成的地方。