我做了一个简单的程序:
其中运行主程序->类程序->二类
让我们看看代码:
主程序:
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/