如何将信号从线程连接到插槽
How to connect a signal from a thread to a slot?
我只想做的是将线程内的信号连接到主线程中的插槽以处理UI更改。
这基本上是我的线程的当前状态,没有什么花哨的,但它仅用于测试目的 atm:
// synchronizer.h
class Synchronizer : public QObject
{
Q_OBJECT
public:
Synchronizer();
signals:
void newConnection(std::wstring id);
private:
QTimer timer;
private slots:
void synchronize();
}
// synchronizer.cpp
Synchronizer::Synchronizer()
{
connect(&timer, SIGNAL(timeout()), this, SLOT(synchronize()));
timer.start();
}
void Synchronizer::synchronize()
{
emit newConnection(L"test");
}
以下是我的主窗口的外观:
// mainwindow.h
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
Synchronizer synchronizer;
private slots:
void addConnection(std::wstring id);
}
// mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(&synchronizer, SIGNAL(newConnection(std::wstring)),
this, SLOT(addConnection(std::wstring)));
QThread *thread = new QThread;
// The problems starts here?
synchronizer.moveToThread(thread);
thread->start();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::addConnection(std::wstring id)
{
// Add a new connection to QListWidget
ui->connectionList(QString::fromStdWString(id));
}
如果我删除那里的行:
synchronizer.moveToThread(thread);
thread->start();
一切似乎都按预期工作,即每秒都会向 QListWidget 添加一个新项目,但是一旦我将同步器对象移动到线程,它就会停止工作。我认为它与连接上下文有关,但我不确定应该如何实现这样的事情,因为我对 Qt 很陌生。
在这种情况下,似乎只是因为我使用 std::wstring 作为信号中的参数,而没有先注册类型,然后在将以下行qRegisterMetaType<std::wstring>("std::wstring");
添加到代码后,一切都按预期工作。
如果我更仔细地阅读输出控制台,我会毫不费力地解决问题,因为它清楚地表明:
QObject::connect: Cannot queue arguments of type 'std::wstring'
所以简单地说,阅读编译器输出,不要像我一样愚蠢:)
相关文章:
- 升压信号2将插槽传递到成员功能以断开连接
- 如何在qt中将信号和插槽与另一个对象连接 --解决了
- QObject::连接无法将信号连接到*this*对象的插槽
- Qt5:连接:如果插槽的参数少于信号,如何使用"连接"
- 使用std::bind将Qt信号连接到插槽
- 使用信号和插槽连接多个 UI 对象
- 如果代码中没有连接任何插槽,是否有理由发出Qt信号?
- 连接来自 C++98 接口的 Qt 插槽和信号,无需 Qt、STL 或 Boost
- 连接信号(Qstring)白色插槽(字符串)的2个不同类别
- 文档在哪里说明如果参数不是从末端删除参数,则无法从QT信号插槽连接中删除参数?
- 连接 -> 窗口上没有这样的插槽
- 如何将信号连接到类的所有实例的插槽
- 通过排队的QT信号插槽连接发送QSHAREDPOINTERS的QVECTOR
- Qt转发插槽/连接插槽到插槽?
- 信号和插槽的连接(有关QListView)-QT
- 我可以交换QObject儿童保持信号和连接的插槽吗?
- Qt按钮无法连接插槽
- 如何使用C 插槽连接QML信号
- qnetworkAccessManager一个实例并连接插槽
- 在Qt中连接插槽