Search code examples
qtqprogressbarqlistwidgetitem

Change property of random element in QListWidget


I have 5 QProgressBars in a QListWidget (ui->listWidget). How can I access the third QProgressBar element and change its value ex. ( progressBar->setValue(40) )

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    a = new QPushButton(this);

    connect(a, SIGNAL (clicked()),this, SLOT (clickedSlot()));
}

void MainWindow::clickedSlot() 
{
    QProgressBar *prog = new QProgressBar(this);

    QListWidgetItem *it;

    it = new QListWidgetItem(ui->listWidget);
    ui->listWidget->insertItem(ui->listWidget->size().height(),it);
    it->setSizeHint(QSize(200,50));

    ui->listWidget->setItemWidget(it, prog);
}

Solution

  • The following code will obtain the third element in the list and set the progress to 40%.

    QProgressBar *bar = qobject_cast<QProgressBar*>(ui->listWidget->itemWidget(pList->item(2)));
    if (bar)
        bar->setValue(40);
    

    qobject_cast will safely cast the QWidget to QProgressBar, only if the widget is indeed a QProgressBar. If you are sure the third element is a QProgressBar, you can omit the if test if(bar).

    See the qt documentation QListWidget and qobject_cast for more information.