0

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);
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
How to
  • 103
  • 1
  • 11

2 Answers2

1

Create the definition for the QProgressBar(s) in the class header file, then you can connect things to the setValue slot, or access them directly.

It seems odd to be adding ProgressBars to QListWidgetItems... wouldn't QHBoxLayout be more suitable?

peeldog
  • 177
  • 9
  • mainwindow.h QProgressBar *prog; MainWindows.cpp prog =new QProgressBar(this); how ? i tried ui->listWidget->item(0)->setValue(100); but QProgressBar[0] not accesable – How to Feb 19 '17 at 18:34
1

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.

m7913d
  • 10,244
  • 7
  • 28
  • 56