QT 从不同的 class 连接信号和插槽到主窗口 class?

QT connect signal and slot in from different classes to mainwindow class?

我想在两个 classes mainwindowreader 之间实现信号和槽。

readerclass里面我声明信号SetProgress:

reader.h

class reader :public QObject
    {
        Q_OBJECT    
         signals:
             void SetProgress(QString sOperation, int nPercentage);
}

reader.cpp

 void reader::UpdateProgress(double amount)
{
     int nPrecentage = (100 * amount / (max- min));
     emit SetProgress(m_sCurrentOperation, nPrecentage); 
}

mainwindow.h

    public:
    reader *MyReader

private slots:

    void SlotDisplayProgress(QString sActivity_i, int ProgressPercentage_i);

mainwindow.cpp

void mainwindow :: SlotDisplayProgress(QString sActivity_i, int nProgressPercentage_i)
{
     this->ui->QprogressBar->setValue(nProgressPercentage_i);
}

里面Mainwidow.cpp我会声明信号和槽

MyReader = reader::New();
connect ( MyReader, &reader::SetProgress, this, &mainwindow::SlotDisplayProgress );

我试过调试,一切正常,直到 emit 部分。但是,slot 永远不会执行。

MyReader 是指针吗?如果不是这样,请使用 &MyReader。

尝试设置 Qt::DirectConnection:

connect ( MyReader, &reader::SetProgress, this, &mainwindow::SlotDisplayProgress, ***Qt::DirectConnection***);

我遇到过这样的问题,我连接了信号和插槽,但只有在我定义了连接类型时它才起作用。

希望对您有所帮助。


PS。我不知道这是否取决于 QT 的版本,但是当我连接信号和插槽时,我编写的语法如下:

ImageURLLoadListener* downloader = new ImageURLLoadListener(&id, socket);
connect(downloader, SIGNAL(imageLoaded(QString*,QTcpSocket*)), this, SLOT(on_resourceImageDownload(QString*,QTcpSocket*)), Qt::DirectConnection);

不知道有没有关系...