在调用exec之前,更新Qt图像不起作用

时间:2016-08-03 06:19:49

标签: c++ qt

我需要创建一个显示图像的简单GUI,此示例中的图像可以更改,GUI将需要更新它的内容。

我在widget类中编写了以下更新函数:

Unhandled JS Exception: SyntaxError: Unexpected token ':'. Parse Error

我尝试以下列方式使用它:

void myClass::updatePic() {
  QPixmap pix("./pic.png");
  int width = ui->picLabel->width();
  int height = ui->picLabel->height();
  ui->picLabel->setPixmap(pix.scaled(width,height,Qt::KeepAspectRatio));}

但窗口刚打开,在我们到达int main(int argc, char *argv[]) { QApplication a(argc, argv); myClass w; w.show(); sleep(3); w.updatePic(); sleep(3); w.updatePic(); sleep(3); return a.exec();} 行之前不会显示图像,然后它会打开最后一张图像。我做错了什么?

编辑:

澄清,更改图像的触发器来自外部程序(具体来说,gui将是ros中的节点,并将由另一个节点触发)。有没有办法通过外部程序按下gui按钮?计时器会工作,但我不喜欢这个"忙等待"风格解决方案。

感谢目前为止的建议

3 个答案:

答案 0 :(得分:2)

exec运行QT事件循环,其中包括渲染小部件。

因此,将您的updatePic电话移动到您的小部件中并通过例如按钮或在展示活动中激活它

答案 1 :(得分:1)

首先了解有关事件循环的更多信息。特别是,您必须知道所有事件(如paintEventresizeEvent)通常都会在相应的事件句柄上调用。事件句柄通常由事件循环调用,即在exec函数内部。

让我们联合@MohaBou和@RvdK的答案。您需要在exec电话后处理定时拍摄。请使用QObject::timerEvent

myClass::myClass()
{
    <...>

    // This two variables are members of myClass.
    _timerId = startTimer(3000);
    _updatesCount = 0;
}

myClass::~myClass()
{
    <...>

    // For any case. As far as I remember, otherwise the late event
    // may be handled after the destructor. Maybe it is false, do
    // not remember...
    if (_timerId >= 0) {
        killTimer(_timerId);
        _timerId = - 1;
    }
}

myClass::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == _timerId) {
        if (_updatesCount < 2) {
            updatePic();
            ++_updatesCount;
        } else {
            killTimer(_timerId);
            _timerId = - 1;
        }
    }
}

此处startTimer方法每隔3秒向事件查询添加特殊的计时器事件。作为所有事件,只有在事件循环将控制并且处理所有早期事件时才可以处理它。因此,如果有很多&#34;重&#34;处理事件。

编辑:抱歉,我在第一次阅读时并没有理解@MohaBou。他明确QTimer的答案也很好(但我仍然不理解模态的一部分)。

答案 2 :(得分:0)

函数exec还呈现子窗口小部件。 exec()阻止应用程序流,而show()不会。因此,exec主要用于模态对话框。

我建议您使用刷新计时器在自定义witget中更新它。使用QTimer每3秒更新一次图像:

QTimer* timer = new QTimer(this);
timer->setInterval(3000);
connect(timer, SINGAL(timeout()), this, SLOT(updatPicture()));

在自定义插槽中更新您的照片:

MainWindow::updatePicture() {
    updatePic()
}

如果需要,可以使用lambda函数:

connect(timer, &QTimer::timeout, this,  [&w]() {
    updatePic()
});