修改qt QTableView裡的modal資料並更新資料
阿新 • • 發佈:2019-02-16
1.當表格有某行被選擇時,獲取所選行的QModelIndex並呼叫setData函式
int row = ui.tv_searchList->currentIndex().row();
//QAbstractItemModel *model = ui.tv_searchList->model();
//m_deviceTableModel是qtableview關聯的modal類
QModelIndex index_Name = m_deviceTableModel->index(row, 6);//選中行第7列的內容
QModelIndex index_Pwd = m_deviceTableModel->index(row, 7);//選中行第8列的內容
m_deviceTableModel->setData(index_Name, QVariant::fromValue(name));
m_deviceTableModel->setData(index_Pwd, QVariant::fromValue(password));
2.修改Modal 裡的SetData函式(本人只是想修改第7列和第8列的資料)
程式碼裡的自定義modal類DeviceTableModel是繼承了public
QAbstractItemModel的
過載函式宣告:
bool DeviceTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
函式體裡關鍵程式碼如下:
if (role == Qt::EditRole )//setData引數不指定的話 role 預設就為Qt::EditRole
{
if (index.column() == 6)
{
m_devList->at(index.row()).personalUserName = value.toString().toStdString();
}
if (index.column() == 7)
{
m_devList->at(index.row()).personalPassword = value.toString().toStdString();
}
}
emit this->dataChanged(index, index);