Qt598x64vs2017.跨线程传递std::string

1、Qt编译的时候 提示 str::string 需要在main(...)中注册什么的(大概是这个意思,记不清了),于是 在main(...)中调用了 “qRegisterMetaType<std::string>("std::string");

  提示 “str::string&”需要注册的话,是这样注册的:“qRegisterMetaType<std::string>("std::string&");

2、测试代码:

 2.1、MainWindow.h

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_pbtnThread_clicked();
    void slot01(std::string str);
};

class TthreadZ :public QThread
{
    Q_OBJECT
public:
    explicit TthreadZ(QObject *parent = nullptr){ }
    ~TthreadZ(){}

protected:
    void run();

signals:
    void signal01(std::string str);

};

 2.2、MainWindow.cpp

void MainWindow::slot01(std::string str)
{
    DWORD dwThreadId = ::GetCurrentThreadId();

    qDebug() << "MainWindow.dwThreadId : " << dwThreadId << ", " << str.c_str();
}

void MainWindow::on_pbtnThread_clicked()
{
    TthreadZ* p = new TthreadZ();

    connect(p, &TthreadZ::signal01, this, &MainWindow::slot01);// ZC: 注意这里的参数 函数指针

    p->start();
}



void TthreadZ::run()
{
    while (1)
    {
        DWORD dwThreadId = ::GetCurrentThreadId();


        DWORD dw1 = ::GetTickCount();
        std::string str = std::to_string(dw1);
        emit signal01(str);// <-- <-- <-- <-- <--
        DWORD dw2 = ::GetTickCount();

        qDebug() << "TthreadZ.dwThreadId : " << dwThreadId;// << ". Take time : " << dw1 << " --> " << dw2 << " : " << (dw2-dw1)<<"ms";

//        if (g_pMainWindow != nullptr)
//            g_pMainWindow->UpdateCnt();

        Sleep(1000);
        //qDebug() << "";
    }
}

 2.3、main.cpp

#include <string>
using namespace std;

int main(int argc, char *argv[])
{
    qRegisterMetaType<std::string>("std::string");// <-- <-- <-- <-- <--

    QApplication a(argc, argv);

    MainWindow w;
    w.show();

    return a.exec();
}

 

3、

4、

5、

 

posted @ 2019-11-19 15:43  CppSkill  阅读(413)  评论(0编辑  收藏  举报