Qt c++不会为所有对象调用move_slot.为什么?

Qt c++ does not call the move_slot for all objects. Why?

本文关键字:move 调用 slot 为什么 对象 c++ Qt      更新时间:2023-10-16
int forIterator = 0;
Scenes::Scenes(QWidget * parent): QObject ()
{
setScene(scene);
for(int i = 0; i < Dot::number_of_dotz; i++)
{
QTimer *timer_move = new QTimer();
QObject::connect(timer_move,SIGNAL(timeout()),dotz[i],SLOT(move_slot()));
timer_move->start(10);
}

Dot::number_of_dots 在 move_slot(( 中更新(+1(,因为创建了一个新点,但从未调用新点的move_slot。 为什么会这样(不(发生?

看来你应该在move_slot()创建一个新的Dot。 当 Dot::number_of_dotz 静态成员的值大于 0 时Scenes::Scenes(QWidget * parent)调用构造函数,并且可能您已经在其中创建了一些点实例。因此,Scene构造函数被调用一次,就不会再次调用。

很明显,您这样做是因为您想在创建Scenes类后开始扩展 dotz。

我的解决方案是检查move_slot()中的sender()类型,如果是 QTimer,您可以在move_slot()本身中创建新QTimer

我建议您为QTimer设置父级以防止内存泄漏。

void Dot::move_slots(){
// your code 
QTimer *caller_object = qobject_cast<QTimer*>(sender());
// caller_object will be nullptr if this slot is not being called
// by an object other than a QTimer
if(caller_object){   
QTimer *timer_move = new QTimer(this);
QObject::connect(timer_move,SIGNAL(timeout()),this,SLOT(move_slot()));
timer_move->start(10);
}
}

我希望我对你想要实现的目标的假设是正确的。如果不是这种情况,请发表评论。