QT5 插槽未在子类中调用

QT5 Slot not called in subclass

本文关键字:调用 子类 插槽 QT5      更新时间:2023-10-16

我有一个超类BackgroundWorkerWithWaitDialog,它管理一个WaitDialog,该实现了带有"中止"按钮的进度条框。它被用作QThread中的QObject。

我的目的是从 BackgroundWorker 派生任何后台任务,并仅实现 execute() 命令,轮询 aborted 标志以阻止它。

BackgroundWorkerWithWaitDialog派生自QObject BackgroundWorker,所有类都Q_OBJECT,worker类能够使用信号和插槽更新GUI。此通信(工作线程到 GUI 对象(工作正常。

问题在于,尽管 WaitDialog 响应按钮单击,但 WaitDialog 发出aborted()信号,但 BackGroundworker 不会接收到。(桂->工人(

class WaitDialog : public QDialog
{
    Q_OBJECT
public:
    explicit WaitDialog(QWidget *parent = 0);
    ~WaitDialog();
public slots:
    void setText(QString text);
    void setProgress(bool shown, int max);
    void enableAbort(bool enable);
    void setProgression (int level);
signals:
    void aborted();
private slots:
    void on_cmdAbort_clicked();
private:
    Ui::WaitDialog *ui;
};

void WaitDialog::on_cmdAbort_clicked()
{
    qDebug() << "ABORT";
    emit aborted();
}

/// BackgroundWorker is QObject-derived.
class BackgroundWorkerWithWaitDialog : public BackgroundWorker
{
    Q_OBJECT
public:
    explicit BackgroundWorkerWithWaitDialog(MainWindow *main, WaitDialog *dialog);
...
public slots:
    virtual void abortIssued();

....

BackgroundWorkerWithWaitDialog::BackgroundWorkerWithWaitDialog(MainWindow *main, WaitDialog *dialog)
: BackgroundWorker(main),
  mWaitDialog(dialog),
  mAborted(false)
{
    connect (this, SIGNAL(progress(int)), mWaitDialog, SLOT(setProgression(int)));
    connect (this, SIGNAL(messageChanged(QString)), mWaitDialog, SLOT(setText(QString)));
    connect (this, SIGNAL(progressBarVisibilityChanged(bool,int)), mWaitDialog, SLOT(setProgress(bool,int)));
    connect (this, SIGNAL(abortButtonVisibilityChanged(bool)), mWaitDialog, SLOT(enableAbort(bool)));
    connect (mWaitDialog, SIGNAL(aborted()), this, SLOT(abortIssued()));
}
void BackgroundWorkerWithWaitDialog::abortIssued()
{
    // THIS IS NEVER EXECUTED
    mAborted = true;
}

我错过了什么吗?我暂时使用侦听器模式修复了这个问题,但坦率地说,我不喜欢这种混合修复。

为什么不调用中止的插槽?

提前谢谢。


所以总结一下:

  • BackgroundWorkerWithWaitDialog (BWWWD( 源自继承自 QObject 的 BackgroundWorker
  • BackgroundWorkerWithWaitDialog 在构造函数中接收派生自 QDialog 的 WaitDialog (WD(
  • 构造函数中的 BWWWD 连接((s waitDialog aborted(( 信号与 abortIssued(( 插槽
  • WD 发出信号,但不调用中止已发出
  • BWWWD 在单独的 QThread 中执行

值得一提的是,BWWWD 类是由其他 SpecificWorker 类派生的,这些类实现了利用 aborted(( 函数中断处理的特定函数。

您的问题指出:

我有一个超类 BackgroundWorker 来管理一个 WaitDialog,该对话框实现了一个带有"中止"按钮的进度条框。

BackgroundWorkerWithWaitDialog 构造函数中,不会将dialog传递给 BackgroundWorker 的构造函数,也不会在设置连接时使用 BackgroundWorker 成员变量。

您的问题开场白是错误的,或者您正在连接到从未使用的对话框。