一、table view
table view是用的比较多的一个控件之一,我们在展示数据或者表格的时候经常用到。
二、使用步骤
1、添加表头
QStandardItemModel *m_pTipMdl= new QStandardItemModel();
m_pTipMdl->setColumnCount(4);
m_pTipMdl->setHeaderData(0, Qt::Horizontal, QString::fromLocal8Bit("种族名称"));
m_pTipMdl->setHeaderData(1, Qt::Horizontal, QString::fromLocal8Bit("首发英雄"));
m_pTipMdl->setHeaderData(2, Qt::Horizontal, QString::fromLocal8Bit("二发英雄"));
m_pTipMdl->setHeaderData(3, Qt::Horizontal, QString::fromLocal8Bit("三发英雄"));
ui.tableView->setModel(m_pTipMdl);
ui.tableView->horizontalHeader()->setStretchLastSection(true);
ui.tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui.tableView->verticalHeader()->setDefaultSectionSize(55);
//奇数偶数行不同背景色
ui.tableView->setAlternatingRowColors(true);
//选中整行,每次只允许选中一行
ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
//设置行不能编辑
ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
ui.tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
2、添加行数据
void JxAddLineData
(const char *pstName, const char *pstOne, const char *pstTwo, const char*pstThree)
{
int iCurLine = m_pTipMdl->rowCount();
m_pTipMdl->setItem(iCurLine, 0, new QStandardItem(QString::fromLocal8Bit(pstName)));
m_pTipMdl->item(iCurLine, 0)->setTextAlignment(Qt::AlignCenter);
m_pTipMdl->setItem(iCurLine, 1, new QStandardItem(QString::fromLocal8Bit(pstOne)));
m_pTipMdl->item(iCurLine, 1)->setTextAlignment(Qt::AlignCenter);
m_pTipMdl->setItem(iCurLine, 2, new QStandardItem(QString::fromLocal8Bit(pstTwo)));
m_pTipMdl->item(iCurLine, 2)->setTextAlignment(Qt::AlignCenter);
m_pTipMdl->setItem(iCurLine, 3, new QStandardItem(QString::fromLocal8Bit(pstThree)));
m_pTipMdl->item(iCurLine, 3)->setTextAlignment(Qt::AlignCenter);
}
//调用函数添加数据
JxAddLineData("人族", "大法师", "MK", "帕拉丁");
JxAddLineData("兽族", "剑圣", "小Y", "牛头");
JxAddLineData("精灵", "DH", "兽王", "TK");
JxAddLineData("不死", "DK", "LICH", "小黑");
3、获取双击事件
connect(ui.ctrTV,SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(SktDoubleSlots(const QModelIndex &)));
4、获取选中行内容
void SktDoubleSlots(const QModelIndex &index)
{
QString qsName = m_pTipMdl->data(m_pCtrModel->index(index.row(), 0)).toString();
QString qsOne = m_pTipMdl->data(m_pCtrModel->index(index.row(), 1)).toString();
QString qsTwo = m_pTipMdl->data(m_pCtrModel->index(index.row(), 2)).toString();
QString qsThree = m_pTipMdl->data(m_pCtrModel->index(index.row(), 3)).toString();
}
5、删除行
int iCurLine = ui.ctrTV->currentIndex().row();
QAbstractItemModel *modessl = ui.ctrTV->model();
modessl->removeRow(iCurLine);
三、总结
以上就是QT中TABLE VIEW的使用,其实还有很多属性可以设置,比如是否隐藏表头呀,是否显示网格线呀,QSS样式设置呀等等,欢迎大家留言探讨。