PDA

View Full Version : How to accelerate the loop speed ?



wshn13
2nd May 2013, 04:16
Hi ,all:
I am working on a small program .This program is to show info on a QTableWidget , it may have thousand rows , but the main time waste section is a loop , code like below :

int i=0;
vector<Case>::iterator it = tmp.begin();
for(;it!=tmp.end();it++, i++)
{
table->insertRow(i);
table->setCellWidget( i, 0, new QCheckBox(QString("Y/N")));
table->setItem(i, 1, new QTableWidgetItem(((*it).type)));
table->setItem(i, 2, new QTableWidgetItem(QString((*it).name.c_str())));
table->setItem(i, 3, new QTableWidgetItem(QString((*it).note.c_str())));
}
If I delete the line "table->setCellWidget( i, 0, new QCheckBox(QString("Y/N")));" ,the program will go much more faster ,so that line take the most of the loop run time .What should I do to make the program go faster ?

Added after 18 minutes:

I need some suggestions

ChrisW67
2nd May 2013, 05:35
Don't. Thousands of widgets in a table will not be fast to use, even if you make them faster to create.

QTableWidgetItem supports a check box without the overhead of a widget. Try adapting this:


QTableWidget *table = new QTableWidget(1000, 4);
for(int i = 0; i < 1000; ++i)
{
QTableWidgetItem *item = new QTableWidgetItem("Y/N");
item->setCheckState(Qt::Unchecked);
table->setItem(i, 0, item);
table->setItem(i, 1, new QTableWidgetItem("A"));
table->setItem(i, 2, new QTableWidgetItem("B"));
table->setItem(i, 3, new QTableWidgetItem("C"));
}

wshn13
2nd May 2013, 05:44
Don't. Thousands of widgets in a table will not be fast to use, even if you make them faster to create.

QTableWidgetItem supports a check box without the overhead of a widget. Try adapting this:


QTableWidget *table = new QTableWidget(1000, 4);
for(int i = 0; i < 1000; ++i)
{
QTableWidgetItem *item = new QTableWidgetItem("Y/N");
item->setCheckState(Qt::Unchecked);
table->setItem(i, 0, item);
table->setItem(i, 1, new QTableWidgetItem("A"));
table->setItem(i, 2, new QTableWidgetItem("B"));
table->setItem(i, 3, new QTableWidgetItem("C"));
}


I change code like your advice ,but it work the same . Will QTableView have influence ? Do you have any idea ,thanks!

ChrisW67
2nd May 2013, 05:56
It takes literally 15 milliseconds to execute the loop and create the 4000 items in my example.
Post a complete example program that demonstrates the problem.

BTW: You can resize the table widget once to match the item count of the vector rather than increase it row at a time: QTableWidget::setRowCount().

wshn13
2nd May 2013, 06:45
I redo it ,it works ! thanks!