Search code examples
qtqt5qtablewidgetqlineeditqtablewidgetitem

Qt - Get numbers in specific area (from QLineEdit)


I have a QTableWidget with some columns and rows and want to add a filter for a particular column.

For that, I've added a QLineEdit in my Window. I'm already able to filter the rows, when I add only one number in the QLineEdit:

for(int i=0; i<tableWidget->rowCount(); i++)
{
    if(!tableWidget->item(i, column)->text().contains(lineEdit->text()))
    {
        tableWidget->hideRow(i);
    }
}

(The slot is connected to the textEdited-Signal of the LineEdit)

What I want to do now: When I write something like this in the QLineEdit: 10-30; Hide all rows, which doesnt have the number between 10 and 30 (>=10; <=30).

Somebody has an idea, how I can solve this?


Solution

  • This is my decision.

    Check if lineEdit text contains two numbers.

    QString test = ui->lineEdit->text();
    QStringList lst = test.split('-');
        if (lst.size() == 2)
    

    Transform they in to integers.

    int low = QString(lst[0]).toInt(), high = QString(lst[1]).toInt();
    

    Now let's go to tableWidget and drop in less than or equal to these two numbers.

    for (int i = 1; i <= 100; i++) {
        int row = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(row);
        ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(i)));
    }
    
    connect(ui->lineEdit, &QLineEdit::textChanged, this, [=](const QString &test) {
        QStringList lst = test.split('-');
        if (lst.size() == 2) {
            int low = QString(lst[0]).toInt(), high = QString(lst[1]).toInt();
            for (int i = 0; i < ui->tableWidget->rowCount(); i++) {
                int temp = ui->tableWidget->item(i, 0)->text().toInt();
                if (temp < low || temp > high) {
                    ui->tableWidget->hideRow(i);
                } else {
                    ui->tableWidget->showRow(i);
                }
            }
        }
    });