Qt之模型/视图(实时更新数据)

时间:2025-01-24 10:53:47
TableView::TableView(QWidget *parent)
: QTableView(parent)
{
this->setAlternatingRowColors(true);
this->setStyleSheet( "QTableView{background-color: rgb(250, 250, 115);"   
"alternate-background-color: rgb(141, 163, 215);}" ); 
this->setSelectionBehavior(QAbstractItemView::SelectRows);
this->horizontalHeader()->setStretchLastSection(true);
this->horizontalHeader()->setHighlightSections(false); 
this->verticalHeader()->setVisible(false);
this->setShowGrid(false);
this->setEditTriggers(QAbstractItemView::NoEditTriggers);
this->setSelectionMode(QAbstractItemView::ExtendedSelection);

    model = new TableModel();
    this->setModel(model);
    this->initHeader();
    model->setModalDatas(&grid_data_list);
    progressbar_delegate = new ProgressBarDelegate();
    this->setItemDelegate(progressbar_delegate);

connect(model, &TableModel::updateCount, this, &TableView::updateCount);

    this->initHeader();
}

TableView::~TableView(void)
{
    if(progressbar_delegate) {
        delete progressbar_delegate;
        progressbar_delegate = NULL;
    }

    if(model) {
        delete model;
        model = NULL;
    }
    grid_data_list.clear();
}

void TableView::addRow(QStringList rowList)
{
    grid_data_list.append(rowList);
    model->refrushModel();
}

void TableView::remove()
{
QModelIndexList model_index_list = this->selectedIndexes();
int model_count = model_index_list.count();
if(model_count <= 0)
return;

QList list_row;
for(int i=model_count-1; i>=0; i--)
{
QModelIndex model_index = model_index_list.at(i);
int row = model_index.row();
if(!list_row.contains(row))
list_row.append(row);
}

if(list_row.isEmpty())
return;

qSort(list_row);

for(int i=list_row.count()-1; i>=0; i--)
{
grid_data_list.removeAt(list_row.at(i));
}

model->refrushModel();
}

void TableView::clear()
{
grid_data_list.clear();
model->refrushModel();
}

int TableView::rowCount()
{
return model->rowCount(QModelIndex());
}

void TableView::initHeader()
{
    QStringList header;
    header << tr("name") << tr("size") << tr("progress") << tr("speed") << tr("left time") << tr("state");
    model->setHorizontalHeaderList(header);
}

void TableView::changeValue()
{
//这里以10行尾列进行更新
int row_count = this->rowCount();
if(row_count < 10)
return;

for(int i=0; i<10; i++)
{
QStringList file_list = grid_data_list.at(i);
int progress = rand()0;
QStringList row_list;
row_list <<  file_list.at(0) << file_list.at(1) << QString::number(progress) << file_list.at(3) << file_list.at(4) << file_list.at(5);
grid_data_list.replace(i, row_list);
}

model->refrushModel();
}