1

我遇到了一个愚蠢的问题,而且我对 Qt 还是很陌生。

我有一个类 ( SoundSampler ),它从基类 ( BaseSampler )继承信号,并且该信号在 UI 构造函数 ( MainWindow ) 中连接到 UI 中的插槽 ( sampleAvailable() )。

问题:

即使连接发生正确(connect()在 UI 类中返回 true,并且isSignalconnectedSoundSampler类中也返回 true),但永远不会调用插槽。..................................................... ...................................

这是我的代码(精简为要点):

基本采样器

class BaseSampler : public QObject
{
    Q_OBJECT
public:
    explicit BaseSampler(QObject *parent = 0);
    void getSample();

signals:
    void sampleAvailable(QByteArray *returnSample);
public slots:
    virtual void getSample() = 0;

protected:
    QByteArray *mSample;
};

声音采样器

class SoundSampler : public BaseSampler
{
    Q_OBJECT
public:
    SoundSampler();

signals:

public slots:
    void stopRecording();
    void getSample();

private:
    QAudioInput *mAudioInput;
    QBuffer *mBuffer;
};

..................................................... ...................................

void SoundSampler::stopRecording(){
    ...
    mSample->append("test");
    emit sampleAvailable(mSample);
    qDebug() << "Signal emmited"; //this get properly displayed in output
}

主窗口

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

public slots:
    void sampleHandler(QByteArray*);

private:
    QWidget *window;
    SoundSampler *ss;
};

..................................................... ...................................

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    window = new QWidget();
    ss = new SoundSampler();

    boutonStart = new QPushButton(tr("&Start"));

    layout = new QHBoxLayout;
    layout->addWidget(boutonStart);

    window->setLayout(layout);
    window->show();

    connect(boutonStart, SIGNAL(clicked()),
            ss, SLOT(getSample())); //This connection works
    //The getSample() starts a Timer witch successfully calls the stopRecording slot

    connect(ss, SIGNAL(sampleAvailable(QByteArray*)),
            this, SLOT(sampleHandler(QByteArray*))); //This connection should work
    //The connect returns true, indicating the connection happend.

}

//This slot is never called.
void MainWindow::sampleHandler(QByteArray *sample){
    qDebug() << "Passed Value: " << *sample;
}
4

1 回答 1

1

好的,我解决了。

问题不在 MainWindow 类中,而是在调用它的类中……我的同事实施得很糟糕(MainWindow 实例化的对象仅在构造函数中,而不是作为类的成员)。

因此,一旦构造函数完成,插槽就会被取消注册。

(抱歉弄得一团糟,无论如何谢谢你 vahancho ;) )

于 2013-12-03T15:16:39.067 回答