【发布时间】:2014-12-09 12:50:33
【问题描述】:
我有一个超类BackgroundWorkerWithWaitDialog,它管理一个WaitDialog,它实现了一个带有“中止”按钮的进度条框。它在 QThread 中用作 QObject。
我的意图是从 BackgroundWorker 派生任何后台任务并仅实现 execute() 命令,轮询 aborted 标志以停止它。
BackgroundWorkerWithWaitDialog 派生自BackgroundWorker,它是一个 QObject,所有类都是 Q_OBJECT,并且工作类能够使用信号和槽更新 gui。这种通信(Worker 到 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;
}
我有什么遗漏吗?我暂时用监听器模式修复了这个问题,但坦率地说,我不喜欢这种混合修复。
为什么不调用 abortIssued 插槽?
提前致谢。
总结一下:
- BackgroundWorkerWithWaitDialog (BWWWD) 从继承自 QObject 的 BackgroundWorker 派生
- BackgroundWorkerWithWaitDialog 在构造函数中接收派生自 QDialog 的 WaitDialog (WD)
- BWWWD 在构造函数 connect() 中使用 abortIssued() 槽传递 waitDialog aborted() 信号
- WD 发出信号,但未调用 abortIssued
- BWWWD 在单独的 QThread 中执行
值得一提的是,BWWWD 类是由其他 SpecificWorker 类派生的,这些类实现了利用 aborted() 函数中断处理的特定函数。
【问题讨论】:
标签: c++ qt signals-slots