删除几行后,我尝试删除所有行,它变得非常慢

时间:2019-07-05 03:24:53

标签: c++ qt

最初,我创建一个内部包含许多行的QTableView,并使用QStandardItemModel来管理数据。通过setSortingEnabled(True)启用排序。通过单击标题对数据进行排序后,我尝试删除所有行,但是速度非常慢。我用QSortFilterProxy解决了这个问题。但是我不知道为什么...

现在,另一个问题是:如果我先删除服务器行,然后尝试选择并删除所有行,它将变得非常慢。

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QDialog>
#include <QTableView>
#include <QVBoxLayout>
#include <QStandardItemModel>
#include <QPushButton>


class MainWindow : public QDialog
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    QTableView *tableView;
    QVBoxLayout *mainLayout;
    QStandardItemModel *tableModel;
    QHBoxLayout *btLayout;
    QPushButton *deleteAllBt;
    QPushButton *delete10;

    ~MainWindow();


private:
    int col;
    void retranslateUi();

private slots:
    void delete10Rows();
    void deleteAllRows();
};

#endif // MAINWINDOW_H

mainwindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent) :
    QDialog(parent)
{
    tableView = new QTableView;
    tableModel = new QStandardItemModel;
    mainLayout = new QVBoxLayout;
    btLayout = new QHBoxLayout;
    delete10 = new QPushButton;
    deleteAllBt = new QPushButton;

    tableView->setAttribute(Qt::WA_DeleteOnClose);
    tableView->setSortingEnabled(true);
    tableView->setModel(tableModel);

    btLayout->addWidget(delete10);
    btLayout->addWidget(deleteAllBt);
    btLayout->addStretch();

    mainLayout->addWidget(tableView);
    mainLayout->addLayout(btLayout);
    setLayout(mainLayout);


    connect(delete10, SIGNAL(clicked()), this, SLOT(delete10Rows()));
    connect(deleteAllBt, SIGNAL(clicked()), this, SLOT(deleteAllRows()));

    retranslateUi();
    resize(QSize(600, 480));

    col = 46;
    for(auto i = 0; i < 10000; i++)
    {
        QList<QStandardItem *> items;
        for(auto j = 0; j < col; j++)
        {
            items.append(new QStandardItem(tr("Test %1 x %2").arg(i).arg(j)));
        }
        tableModel->appendRow(items);
    }
}

MainWindow::~MainWindow()
{

}

void MainWindow::retranslateUi()
{
    setWindowTitle(tr("Test"));
    delete10->setText(tr("Delete 10 Rows"));
    deleteAllBt->setText(tr("Delete All"));
}

void MainWindow::delete10Rows()
{
    tableModel->removeRows(10, 10);
}

// ATTENTION: Remove 10 rows first, and then try to remove all rows, it's extremely slow.
void MainWindow::deleteAllRows()
{
    for(auto row = tableModel->rowCount(); row >= 0;)
    {
        tableModel->removeRow(--row);
    }
}

0 个答案:

没有答案