【问题标题】:Qt Threads call FunctionQt 线程调用函数
【发布时间】:2015-07-11 11:25:01
【问题描述】:

我有一个“A”类,在这个类中有一个方法“method1()”,method1 在 qthread 中运行。在方法 1 中,我想调用 MainWindow 类中的一个函数,如下所示:'MainWindow window; window.func()'

当我这样做时,我收到以下错误消息:QObject::setParent: Cannot set parent, new parent is in a different thread

这是我的代码:

void gCode_int::parse_File(char* gCode_file, int file_length,MainWindow *window)
{
    window->fahre_on_pos(NULL,atoi(x_pos.c_str()),atoi(y_pos.c_str()));
}

这里是MainWindow中的函数:

void MainWindow::fahre_on_pos(char* g_command ,int x_pos, int y_pos)
{    
double y_schritte;
double x_schritte;

int j =  1;
int x_length = x_pos-x_pos_old;
int y_length = y_pos-y_pos_old;

digitalWrite(x_treiber,1);
digitalWrite(y_treiber,1);

if(x_length > 0)
{
    digitalWrite(x_richtung, 1);
}
if(x_length <= 0)
{
    digitalWrite(x_richtung,0);
    x_length *= -1;
}

if(y_length > 0)
{
    digitalWrite(y_richtung, 0);
}
if(y_length < 0)
{
    digitalWrite(y_richtung,1);
    y_length *= -1;
}
y_schritte = round((y_length/1.25)*48);

if(y_schritte == 0)
{
    y_schritte =1;
    digitalWrite(y_treiber,0);
}
if(x_schritte == 0)
    digitalWrite(x_treiber,0);

x_schritte = round(((x_length/1.25)*200)/y_schritte);
while(j <= y_schritte)
{
    for(int i=1;i<= x_schritte;i++)
    {
        digitalWrite(x_v, 1);
        delay(1);
        digitalWrite(x_v, 0);
        delay(1);
    }
    if(x_schritte == 0)
    {
        digitalWrite(y_v, 1);
        delay(4);
        digitalWrite(y_v, 0);
        delay(4);
    }
    else
    {
        digitalWrite(y_v, 1);
        delay(1);
        digitalWrite(y_v, 0);
        delay(1);
    }
    j++;
}
x_pos_old = x_pos;
y_pos_old = y_pos;

}

希望有人可以帮助我

【问题讨论】:

    标签: c++ multithreading qt


    【解决方案1】:

    在 MainWindow 中创建一个槽,它从带有信号的线程接收参数并调用方法

    Qt - updating main window with second thread

    【讨论】:

      【解决方案2】:

      来自http://doc.qt.io/qt-5/threads-qobject.html

      虽然 QObject 是可重入的,但 GUI 类,尤其是 QWidget 及其所有子类,不是可重入的。它们只能在主线程中使用。如前所述,还必须从该线程调用 QCoreApplication::exec()。

      实际上,通过将耗时的操作放在单独的工作线程中并在工作线程启动时在主线程的屏幕上显示结果,可以轻松解决在主线程以外的其他线程中使用 GUI 类的不可能的问题。完成了

      信号和槽应该在worker和主窗口之间建立连接,否则如上所述它将不起作用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-14
        • 2021-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-17
        • 2022-01-05
        相关资源
        最近更新 更多