Qt更改计时器

时间:2015-10-28 13:09:19

标签: c++ qt qtimer

我正在尝试在Qt中更改QLabel上的图像。

首先,我做了如下基本设置图像:

void MainWindow::setMainDisplayNew(QString imageName){
     QPixmap pix7 = imageName;
     QPixmap pix8 = pix7.scaled(QSize(720,480), Qt::KeepAspectRatio);
     ui->mainDisplay->setStyleSheet(imageName);
     ui->mainDisplay->setPixmap(pix8);
}

现在我想改变它,所以我可以传递2个数组。应显示的图像列表和持续时间,我希望显示屏显示指定的持续时间。

        void MainWindow::setMainDisplay(QString imageName[], int size)
{
    for(unsigned int i=0; i<size; i++)
    {
        QTimer * timer = new QTimer(this);
        timer->setSingleShot(true);
        connect(timer, &QTimer::timeout, [=](){
            setMainDisplayNew(imageName[i]);
            timer->deleteLater(); // ensure we cleanup the timer
        });
        timer->start(3000);
    }
}

修改

在回复的帮助下,我达到了上述代码。我正在发送3张图片。它会在3秒后显示最终图像并保持原样...任何帮助?

1 个答案:

答案 0 :(得分:4)

while(true){

这是你的问题。 Qt是event-driven framework while(true)可防止处理事件。此类事件包括QTimer的超时和GUI的更新。您需要允许该函数退出。

此外,您还没有清理定时器,因此每次进入此功能时都会泄漏内存(尽管目前只有一次!)。您可以通过调用deleteLater进行清理。

使用C++ 11,它将是这样的: -

for(int i=0; i<mySize; i++)
{
    QTimer * timer = new QTimer(this);
    timer->setSingleShot(true);

    connect(timer, &QTimer::timeout, [=](){
        setMainDisplayNew(imageName[i]);
        timer->deleteLater(); // ensure we cleanup the timer
    });

    timer->start(duration[i]);
}