Qt插槽方法(这是另一个类)在发出信号时不触发

时间:2017-01-22 23:15:10

标签: c++ visual-studio qt

我知道这个问题很多次,但仍然困惑,无法找到解决方案。

我有一个MainWindow和一个类。

在我班上,我有一个信号,我在方法调用中发出。

问题:Slot方法没有触发。

这是我的代码。

BWorker.h

#pragma once

#include <QObject>

class BWorker : public QObject
{
    Q_OBJECT

public:
    BWorker(QObject *parent);
    ~BWorker();
    void doSomething();

signals:
    void signalSomething();

};

BWorker.cpp

#include "BWorker.h"

BWorker::BWorker(QObject *parent)
    : QObject(parent)
{
}

BWorker::~BWorker()
{
}

void BWorker::doSomething() 
{
    emit signalSomething();
}

QtGuiApplication1.h

#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_QtGuiApplication1.h"

class QtGuiApplication1 : public QMainWindow
{
    Q_OBJECT

public:
    QtGuiApplication1(QWidget *parent = Q_NULLPTR);

public slots:
    void workDone();

private:
    Ui::QtGuiApplication1Class ui;
};

QtGuiApplication1.cpp

#include "QtGuiApplication1.h"
#include "BWorker.h"

QtGuiApplication1::QtGuiApplication1(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    BWorker bworker(this);

    connect(&bworker, SIGNAL(bworker.signalSomething), this, SLOT(workDone()));

    bworker.doSomething();

}

void QtGuiApplication1::workDone() {

}

2 个答案:

答案 0 :(得分:0)

你的问题在这里:

SIGNAL(bworker.signalSomething)

这是无效的,你应该在终端看到一条消息说没有这样的信号。您案例的正确语法是:

SIGNAL(signalSomething())

答案 1 :(得分:0)

请通过复制粘贴发布您的代码。不要编辑代码:问题可能出现在您编辑的

我的代码工作正常。

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void workDone();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include "worker.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    Worker worker(this);
    connect(&worker, SIGNAL(signalSomething()), this, SLOT(workDone()));
    //connect(&worker, &Worker::signalSomething, this, &MainWindow::workDone);
    worker.doSomething();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::workDone()
{
    qDebug() << "Done.";
}

worker.h:

#ifndef WORKER_H
#define WORKER_H

#include <QObject>

class Worker : public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent = 0);
    void doSomething();
signals:
    void signalSomething();
public slots:
};

#endif // WORKER_H

worker.cpp:

#include "worker.h"

Worker::Worker(QObject *parent) : QObject(parent)
{

}

void Worker::doSomething()
{
    emit signalSomething();
}

申请表输出:

Debugging starts
Done.
Debugging has finished

打印出来&#34;完成。&#34;意味着代码正在运作。