Qt-在不同的线程中使用信号和槽
Qt-Using signals and slots with different threads
我仍在努力使它按预期工作。
我有一个 Qt 项目,我想根据来自不同线程的信号状态对其进行更新。我的主 GUI 线程应该在按下启动按钮时启动一个工作线程 运行ning。
工作线程然后应该执行一个函数,该函数连续轮询属于另一个 class 的变量,这些变量甚至被不同的线程更新(我正在使用 portaudio 库)。然后它应该触发一个信号 (sendNewSig),该信号连接到我的 GUI class.
中的插槽 (DrawData)
问题是当我按下开始按钮时程序崩溃了。我相信我错过了一些重要的步骤来开始执行工作线程。通过在单击开始按钮时像这样调用 updater->PollSignal() ,我希望它在新线程中达到 运行 但也许不会。我已经展示了下面的部分代码,希望这些代码足以让我的想法得到理解。
非常感谢您的帮助
在GUIApp.cpp
AudioGuiApplication::AudioGuiApplication(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
//...... other stuff
thread = new QThread(this);
updater = new GUIUpdater(&audio_processor);
updater->moveToThread(thread);
connect(updater, SIGNAL(sendNewSig(string)), this, SLOT(DrawData(string)));
connect(thread, SIGNAL(destroyed()), updater, SLOT(deleteLater()));
actionText->setPlainText("Press Start to begin ");
}
void AudioGuiApplication::on_startButton_clicked()
{
updater->PollSignal();
}
在GUIUpdater.cpp`
void GUIUpdater::PollSignal()
{
string str;
while (!ap->IsNewDataFound() )
{
emit sendNewSig(str);
ap->SetNewSigFound(false);
}
}`
您正在直接从 main/gui 线程调用 PollSignal
函数。
我认为在所需线程中执行它的最简单方法是使用 Signal & Slot 机制,单发 QTimer
设置为无延迟(0
代表 0 毫秒) :
void AudioGuiApplication::on_startButton_clicked()
{
QTimer::singleShot(0, updater, &GUIUpdater::PollSignal);
}
顺便说一下:您应该考虑转向 "new" connect
syntax,它不依赖于宏,而是允许编译时类型验证。
我仍在努力使它按预期工作。
我有一个 Qt 项目,我想根据来自不同线程的信号状态对其进行更新。我的主 GUI 线程应该在按下启动按钮时启动一个工作线程 运行ning。
工作线程然后应该执行一个函数,该函数连续轮询属于另一个 class 的变量,这些变量甚至被不同的线程更新(我正在使用 portaudio 库)。然后它应该触发一个信号 (sendNewSig),该信号连接到我的 GUI class.
中的插槽 (DrawData)问题是当我按下开始按钮时程序崩溃了。我相信我错过了一些重要的步骤来开始执行工作线程。通过在单击开始按钮时像这样调用 updater->PollSignal() ,我希望它在新线程中达到 运行 但也许不会。我已经展示了下面的部分代码,希望这些代码足以让我的想法得到理解。
非常感谢您的帮助
在GUIApp.cpp
AudioGuiApplication::AudioGuiApplication(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
//...... other stuff
thread = new QThread(this);
updater = new GUIUpdater(&audio_processor);
updater->moveToThread(thread);
connect(updater, SIGNAL(sendNewSig(string)), this, SLOT(DrawData(string)));
connect(thread, SIGNAL(destroyed()), updater, SLOT(deleteLater()));
actionText->setPlainText("Press Start to begin ");
}
void AudioGuiApplication::on_startButton_clicked()
{
updater->PollSignal();
}
在GUIUpdater.cpp`
void GUIUpdater::PollSignal()
{
string str;
while (!ap->IsNewDataFound() )
{
emit sendNewSig(str);
ap->SetNewSigFound(false);
}
}`
您正在直接从 main/gui 线程调用 PollSignal
函数。
我认为在所需线程中执行它的最简单方法是使用 Signal & Slot 机制,单发 QTimer
设置为无延迟(0
代表 0 毫秒) :
void AudioGuiApplication::on_startButton_clicked()
{
QTimer::singleShot(0, updater, &GUIUpdater::PollSignal);
}
顺便说一下:您应该考虑转向 "new" connect
syntax,它不依赖于宏,而是允许编译时类型验证。