[英]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的外觀:
// 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還是很新的。
似乎在這種情況下,這僅僅是我在沒有先注冊類型而是在添加以下行qRegisterMetaType<std::wstring>("std::wstring");
情況下,先在信號中使用std :: wstring作為參數的事實。 qRegisterMetaType<std::wstring>("std::wstring");
到代碼,一切都按預期工作。
如果我會更仔細地閱讀輸出控制台,那么我會很輕松地解決此問題,因為它明確指出:
QObject::connect: Cannot queue arguments of type 'std::wstring'
簡單來說,閱讀編譯器輸出,不要像我一樣愚蠢:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.