在qt中创建qlabel的QVector

Creating a QVector of QLabels in qt

本文关键字:QVector qlabel 创建 qt      更新时间:2023-10-16

我正在尝试创建QLabels的QVector .

我不知道该怎么做。我这样声明我的QVector: QVector<QLabel> labels

在我的。cpp文件中,我想将每个标签设置为一个像素图。我应该首先通过for循环初始化所有实例吗?

在构造函数中:

 for(int i = 0; i < usrinput; i++)
  {
     labels.append(new QLabel);
     setplayerpiece(i);
  }

在构造函数之外有一个函数,它将每个QLabel设置为一个图像:

   void CentralWidget::setplayerpiece(int tk)
{
  if (p[tk]->setpiece() == 0)
  {
    labels[tk]->setPixmap(QPixmap(":/images/hat.png"));
  }
  else if (p[tk]->setpiece() == 1)
  {
    labels[tk]->setPixmap(QPixmap(":/images/car.png"));
  }
  else if (p[tk]->setpiece() == 2)
  {
    labels[tk]->setPixmap(QPixmap(":/images/shoe.png"));
  }
  else if (p[tk]->setpiece() == 3)
  {
    labels[tk]->setPixmap(QPixmap(":/images/spaceship.png"));
  }
  else if (p[tk]->setpiece() == 4)
  {
    labels[tk]->setPixmap(QPixmap(":/images/basketball.png"));
  }
  else if (p[tk]->setpiece() == 5)
  {
    labels[tk]->setPixmap(QPixmap(":/images/ring.png"));
  }
}

我应该在构造函数中运行另一个for循环后,我初始化标签调用函数setplayerpiece为每个实例?本质上我想做的是给每个玩家分配一张图片。如果我说得不清楚,或者你需要更多的信息,请告诉我。谢谢你的帮助。

这个方法如何:

QVector<QString> playerIconPath;

playerIconPath.append(":/images/hat.png");
playerIconPath.append(":/images/car.png");
playerIconPath.append(":/images/shoe.png");
playerIconPath.append(":/images/spaceship.png");
playerIconPath.append(":/images/basketball.png");
playerIconPath.append(":/images/ring.png");
QVector<QLabel*> labels
for(int i = 0; i < playerIconPath.size(); i++)
{
    labels.append(new QLabel);
    labels[i]->setPixmap(QPixMap(playerIconPath[i]));
}