1

How do i define std::string as a type so i can emit from text from a QThread to another using a queued connection?

I searched and found many threads solving this issue.

Here one of the other threads available

Here other thread

But all of them consider the connection as a Qt 4 version. (Signal and slot macros).

Now, after 3 years, with Qt5.2 available, i'm not able to find a solution, even when the documentation says:

Docs about Q_DECLARE_METATYPE

I have to define the type in my header. I tried where Q_OBJECT goes, and outside the class. Apparently outside works.

I tried:

Q_DECLARE_METATYPE<std::string>();
Q_DECLARE_METATYPE(std::string);
Q_DECLARE_METATYPE<std::string>;
Q_DECLARE_METATYPE<std::string>(anothername declared for std::string with typedef);

All of them gave me errors, from: Syntax error : missing ';' before , to unnable to missing type specifier, int assumed. The problem is always with this line of code.

and i´m using this in the same class within a method, which registers the type just before connecting the new thread with a queued connection:

qRegisterMetaType<std::string>();
QObject::connect(worker, &Raytracer::textEmitted, gui_, &MainWindow::addText, Qt::QueuedConnection);

What am i doing wrong?

I got to make it work by using QString. But how could i make it work with std::string?

Community
  • 1
  • 1
Darkgaze
  • 2,280
  • 6
  • 36
  • 59

2 Answers2

2

Q_DECLARE_METATYPE should be placed outside any class or function.

The docs state: Ideally, this macro should be placed below the declaration of the class or struct. If that is not possible, it can be put in a private header file which has to be included every time that type is used in a QVariant.

The correct syntax is Q_DECLARE_METATYPE(std::string) without the ;.

But this is all useless if you are not using templates. As the docs state: Declare new types with Q_DECLARE_METATYPE() to make them available to QVariant and other template-based functions. Call qRegisterMetaType() to make type available to non-template based functions, such as the queued signal and slot connections.

So all you need to do is call qRegisterMetaType, and you will be able to use std::string in your queued connections. Do something like this somewhere before your connect statement:

qRegisterMetaType<std::string>("std::string");
thuga
  • 12,601
  • 42
  • 52
1

Include the qmetatype.h header in the file which uses Q_DECLARE_METATYPE.

steveire
  • 10,694
  • 1
  • 37
  • 48