c++ - QT 插槽和信号失败

标签 c++ qt signals connect slot

您好,我在 qt 中遇到了信号和槽的问题。 在 main 中,我创建了主窗口的对象。 在 mainwindow.cpp 中,我创建了另一个类(modbus_tcp)的对象。 我也在这里创建连接

void MainWindow::on_ConnectB_clicked()
{

    modbus_tcp appts;
    appts.slave();
    connect(&appts,SIGNAL(msgSended(QString)),this,SLOT(msgEdit(QString)));
}

在 mainwindow.cpp/h 中声明的插槽之间

public slots:
void msgEdit(QString m);

void MainWindow::msgEdit(QString m)
{
ui->sendEdit->setText(m);
ui->recvEdit->setText(m);
//QMessageBox::information(0,"bad", "nope nope nope");
}

和在 modbus_tcp.h 中声明的信号

signals:
void msgSended(QString);

接下来我在 modbus_tcp.cpp 中发射信号

emit msgSended("asdasd");

什么也没发生

当我试图在 mainwindow.cpp 中发出它的工作时

有什么想法吗?

最佳答案

void MainWindow::on_ConnectB_clicked()
{

    modbus_tcp appts;
    appts.slave();
    connect(&appts,SIGNAL(msgSended(QString)),this,SLOT(msgEdit(QString)));
}

appts 是在栈中创建的,所以它会在槽执行结束时被删除。尝试在堆中创建它(尝试使用指针)。

void MainWindow::on_ConnectB_clicked()
{

    modbus_tcp *appts = new modbus_tcp;
    connect(appts,SIGNAL(msgSended(QString)),this,SLOT(msgEdit(QString)));//first!
    appts->slave();//now you can call it
}

使用指针,但首先是connect,然后调用slave。你在slave发出信号,但是此时没有连接。您应该先进行连接,然后才能捕获信号。

关于c++ - QT 插槽和信号失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26345950/

相关文章:

c++ - 将按钮添加到 QTableview

c - 信号处理: how to parse code and status so WIFEXITED etc.可以用吗?

c++ - 从函数定义并返回函数?

c++ - 从函数返回 QString - 线程安全?

c++ - 为什么qmap使用skiplist而不是ob rb-tree?

python - celery task_success 与发件人过滤器

python - celery 通过在 task_postrun 信号中提高 SystemExit 来尝试关闭 worker 但总是挂起并且主进程永远不会退出

c++ - QString::mid() 总是返回相同的结果

c++ - 为 .dylib 文件创建 objective-c 包装器

qt - 有没有办法通过 Qt WebChannel 使用同步函数调用?