c++ - QT signal and slots inside second 类

标签 c++ qt signals slot

我做了一个简单的程序:

其中运行主程序->类程序->二类

让我们看看代码:

主程序:

QApplication a(argc, argv);
testqtc w; // this one intresting i call this 'first_class'
w.show();
return a.exec();
}

在 'first_class' 我有:

    testqtc::testqtc(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
    QTimer *timer = new QTimer(this);
    bool p = connect(timer, SIGNAL(timeout()), this, SLOT(updateCaption2()));
    std::cout << p;
    timer->start(1000);

    class1 class1(this); // i call this 'second class' which run under first class
}
void testqtc::updateCaption2(){
    std::cout << "first_class" << std::endl;
}

在“二等舱”我有:

class1::class1(QObject *parent)
    : QObject(parent)
{
    QTimer *timer = new QTimer(this);
    bool p = connect(timer, SIGNAL(timeout()), this, SLOT(updateCaption()));
    std::cout << p;
    timer->start(1000);
}
void class1::updateCaption(){
    std::cout << "second class" << std::endl;
}

输出:

11first_class
first_class
first_class (-> and only first_class per second)

很明显,二级连接器不会启动。 函数 connect 返回 true,但槽没有执行。

如何在'second_class'中使用connect函数?

最佳答案

class1 实例在 testqtc 构造函数中分配在堆栈上,这意味着它在它可以调用超时槽之前被销毁,解决它在堆上分配它:

class1* class1_ptr = new class1 (this);

关于c++ - QT signal and slots inside second 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29049995/

相关文章:

qt - 带标题的 QNetworkRequest

可以在 Linux 的用户空间中实现 native 代码的抢占式多任务处理吗?

python - 模拟 Ctrl-C 到 python 脚本

c++ - 如果变量的值发生变化,则恢复程序

c++ - 如何创建依赖于元组类型名的 boost 元组?

c# - Unity,c++ native 插件不匹配的字节数组

c++ - 调用析构函数会显式地完全销毁对象吗?

c++ - int 测试(无符号整数 i = -1);为什么编译器不生成警告?

qt - 在 ubuntu 22.04 上启动 spyder 时出错

c++ - 尝试获取 QSqlQuery 的值时出现编译错误?