1.类必须继承QObject.
#ifndef TESTA_H #define TESTA_H #include <QObject> class TestA : public QObject { Q_OBJECT public: ); void runTestA(); signals: showMsg(QString str); public slots: }; #endif // TESTA_H
#include "testa.h" #include<QDebug> TestA::TestA(QObject *parent) : QObject(parent) { } void TestA::runTestA() { qDebug()<<"+++runtesta++"; emit showMsg("ssssss"); }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "testa.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: ); ~MainWindow(); TestA *pTestA; private slots: void on_pushButton_clicked(); void onShowMsg(QString str); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
#include "mainwindow.h" #include "ui_mainwindow.h" #include<QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); pTestA=new TestA(this); connect(pTestA,SIGNAL(showMsg(QString)),this,SLOT(onShowMsg(QString))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { pTestA->runTestA(); } void MainWindow::onShowMsg(QString str) { //防止中文乱码 QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf8")); qDebug()<<"+++++onshowmsg+"; }