可以使用几种方法来完成,最简单的一种(不是最聪明的)是建立中间连接,从对象 A 到主窗口,从主窗口到 B
主窗口.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "classa.h"
#include "classb.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
classA *a;
classB *b;
signals:
void TosignalA();
void TosignalB();
public slots:
void emitB();
private slots:
void on_pushButton_clicked();
};
#endif // MAINWINDOW_H
主窗口.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
a = new classA(this);
b=new classB(this);
connect(this,SIGNAL(TosignalA()),this->a,SLOT(emitsig()));
connect(this->a,SIGNAL(signal()),this,SLOT(emitB()));
connect(this,SIGNAL(TosignalB()),this->b,SLOT(on_signal()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::emitB()
{
emit TosignalB();
}
void MainWindow::on_pushButton_clicked()
{
emit TosignalA();
}
类.h
#ifndef CLASSA_H
#define CLASSA_H
#include <QObject>
class classA : public QObject
{
Q_OBJECT
public:
explicit classA(QObject *parent = 0);
signals:
void signal();
public slots:
void emitsig();
};
#endif // CLASSA_H
类.cpp
#include "classa.h"
classA::classA(QObject *parent) :
QObject(parent)
{
}
void classA::emitsig()
{
emit signal();
}
类b.h
#ifndef CLASSB_H
#define CLASSB_H
#include <QObject>
#include <QtGui>
class classB : public QObject
{
Q_OBJECT
public:
explicit classB(QObject *parent = 0);
signals:
public slots:
void on_signal();
};
#endif // CLASSB_H
类b.cpp
#include "classb.h"
classB::classB(QObject *parent) :
QObject(parent)
{
}
void classB::on_signal()
{
QMessageBox *msgBox = new QMessageBox();
msgBox->setText("signal emitted!");
msgBox->exec();
}