c++ - QT : Passing QString to QThread

标签 c++ qt

我想将 QString 传递给线程。使用 this回答, 这是我的代码: 在 MainWindow.cpp 中:

mmthread = new mythread;
        mmthread->start();

        connect(this,SIGNAL(sendtothread(QString)),mmthread,SLOT(getfrom_main(QString)),Qt::QueuedConnection);

        emit sendtothread(mystr);

ma​​inwindow.h中:

signals:
    void sendtothread(QString);

mythread.cpp中:

void mythread::getfrom_main(QString str)
{
    //something
}

mythread.h中:

public slots:
    void getfrom_main(QString);

但似乎 getfrom_main 根本没有被调用。 我的错误在哪里?

编辑:

我有 3 个类似的线程:

mythread.cpp中:

mythread :: mythread()
{
    moveToThread(this);
}
void mythread::run(){
    //something1
}
void mythread::getfrom_main(QString comm)
{
    comment = comm;
    emit message(comment);
}

mythread.h中:

    class mythread : public QThread
{
    Q_OBJECT
public:
    explicit mythread();
    void run();
signals:
    void message (QString);
private:
       QString comment;
public slots:
    void getfrom_main(QString);
};

something1 总是在我的所有线程中执行。但不是关于 getfrom_main。谢谢。

最佳答案

错误:

mythread :: mythread()
{
    moveToThread(this); // you don't need to do it
}

错误的(你真的不需要在你的代码中继承QThread):

void mythread::run()
{
    //something1
    // after "something" you need to run an event loop:
    exec();
}

exec() 将运行一个事件循环来处理所有信号和槽。

关于c++ - QT : Passing QString to QThread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38327359/

相关文章:

c++ - QColor hsl 色调精度

c++ - 人物轮廓的选择

c++ - 如何减少事件总线实现中的耦合

c++ - 如何从 C++ std::istream 中读取固定数量的字节

c++ 编译器可以在用户定义的和编译器生成的复制构造函数之间自由选择吗?

python - PyQt4 - 使用 QItemDelegate 在 QListView 中显示小部件

windows - 如何识别 Qt 应用程序/小部件何时跨显示器拖动

qt - QMake:自动编译目录中的所有文件

c - OpenCV cvHaarDetectObject 错误

c++ - 为什么 g++ 4.9.0 默认有 std::isnan?