将 QLabel 作为参数 Qt C++传递

Passing QLabel as parameter Qt C++

本文关键字:Qt C++ 传递 参数 QLabel      更新时间:2023-10-16

我有一个小GIF,它在带有QMovieQLabel上动画,我希望在GIF的动画完成后,删除Qlabel。我试过这个,但它不起作用:

QMovie *movie = new QMovie("countdown.gif");
QLabel *processLabel = new QLabel(this);
processLabel->setMovie(movie);
movie->start();
QTimer::singleShot(1000, this, SLOT(movie_finished(backgroundLabel)));

这是我的函数:

void movie_finished(QLabel *processLabel){
    processLabel->deleteLater();
}

基本的误解,这是非法的:

QTimer::singleShot(1000, this, SLOT(movie_finished(backgroundLabel)));

您不能为连接提供这样的参数。只需输入SLOT,如下所示:

QTimer::singleShot(1000, this, SLOT(movie_finished(QLabel*)));

(至少)有三种方法可以解决这个问题。首先从插槽中删除QLabel*参数。然后:

  • 使用 QSignalMapper,它基本上封装了下面的两个替代方案。
  • 在某个类中创建一个中间槽,该时隙具有 QLabel* 成员变量,然后在不带参数的槽中使用该变量,并将定时器信号连接到此时隙。
  • 在插槽中使用sender()方法(但这通常被认为是丑陋的,破坏封装,并且首选QSignalMapper)。

这里实际上并不需要使用 QTimer 来同步电影的结尾。

实现此目的的真正简单方法是让电影在完成后删除标签:

connect(movie, SIGNAL(finished()), processLabel, SLOT(deleteLater()));

QMovie 完成后会发出finished()。因此,只需将其连接到QLabel的deleteLater()插槽即可。

因为这可能会让你在删除QLabel

时泄漏QMovie,所以你可能希望将其父级设置为QLabel,因为将其设置为电影并不意味着QLabel实际上清理了它。

QLabel *processLabel = new QLabel(this);
QMovie *movie = new QMovie("countdown.gif");
movie->setParent(processLabel);