简体   繁体   中英

Fast search through QTableWidget rows

I need to search rows through a QTableWidget . Each of the rows in the table contains a field with date and I need to show only rows that are within a specified date interval based on user input. Here is my function:

void nvr::sort()
{

QTableWidget* tabela = this->findChild<QTableWidget*>("NCtable");



QDateEdit* c1 = this->findChild<QDateEdit*>("c1");

QDateEdit* c2 = this->findChild<QDateEdit*>("c2");

// user specified ranges for date
QDate date1 = c1->date();

QDate date2 = c2->date();

//row numbers in table
int rowsNum = tabela->rowCount();

// hide all rows
for(int z = 0; z < rowsNum; z++) {

    tabela->hideRow(z);

}

// show only rows that are within range
for(int z = 0; z < rowsNum; z++) {


    QDateTime dateTime = QDateTime::fromString(tabela->item(z,2)->text(),"dd.MM.yyyy hh:mm");

    QDate date = dateTime.date();

    //date compares
    if ( (date1.operator <=(date)) && (date2.operator >=(date) ) ) {

    tabela->showRow(z);

    }



   }



}

This works fine if i have 200 rows. But when i have 30 000 rows and i surely will, the gui freezes because i suppose the function executes very slow. Any suggestions for faster execution?

It is hard to reproduce your problem, but here is the approach I would take:

  • Create a custom class to store the data of one row, let's call it DataRow .

  • Store those in a QVector<DataRow> , that you can sort by Date1 for example.

  • Loop through this QVector<DataRow> and find the elements that correspond to the criteria.
  • Add those DataRow to a class derived from QAbstractItemModel .
  • Show this model derived from QAbstractItemModel with a QTableView .

QTableWidget is heavyweight and was not really built for speed. It's really convenient to build something quickly with few elements though. QTableView is the one you want, with a custom model inherited from QAbstractItemModel .

Then, when the user requests a new input, you could just wipe the model and restart the process. This is not optimal, but the user should not see the difference. Feel free to add more logic here to keep the good elements and only remove the bad ones.

About the GUI freezing, one way to always avoid that is to have the GUI thread separated from other worker threads. The QThread documentation is exhaustive and can help you set up something like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM