QTableView Experience(Model/View programming)

·

1 min read

1.How to expand the column to fill the whole table?

we can set up one of the columns as stretch, and other columns are fixed, like this

QTableView* tableView = new QTableView();
tableView->setModel(model);

// Put these statements after setting model, otherwise they won't work
tableView->verticalHeader()->setDefaultSectionSize(40);
tableView->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);

2.How to refresh QTableView data?

Use the datachanged() signal to update QTableView, What's more, you should combine QModelIndex

MyModel* model = new MyModel();
QModelIndex topLeftIndex = model->index(0, 0);
QModelIndex bottomRightIndex = model->index(model->rowCount() - 1, model->columnCount() - 1);
// It will update all data, but you can update just part of them
emit model->dataChanged(topLeftIndex, bottomRightIndex, {Qt::DisplayRole});

3.How to insert or remove data?

Qt has provided four functions for us, like insertRow(), insertRows(),removeRow() and removeRows(). However, the parameters are fixed, so we couldn't transfer our data type. But we can write our functions to implement this because what really works are beginInsertRows(), endInsertRows(), beginRemoveRows() and endRemoveRows().

void AddData(Data* data, const QModelIndex &parent, const int& first, const int& last)
{
    beginInsertRows(parent, first, last);
    m_dataList.push_back(data);
    endInsertRows();
}

void RemoveData(Data* data, const QModelIndex &parent, const int& first, const int& last)
{
    auto it = std::find(m_dataList.begin(), m_dataList.end(), data);
    if (it != m_dataList.end())
    {
        beginRemoveRows(parent, first, last);
        m_dataList.erase(it);
        endRemoveRows();
    }
}