第二步,添加模型并与视图绑定,实现在主窗口中编辑表格的功能。
C:\Users\Minwei\Projects\Qt\Sheet\sheetwindow.h:
xxxxxxxxxx
191...
2
3
4...
5class SheetWindow : public QMainWindow
6{
7 ...
8private slots:
9 ...
10 void on_m_selection_currentChanged(
11 QModelIndex const& current, QModelIndex const& previous);
12 ...
13private:
14 ...
15 QStandardItemModel* m_model;
16 QItemSelectionModel* m_selection;
17 ...
18};
19...
C:\Users\Minwei\Projects\Qt\Sheet\sheetwindow.cpp:
xxxxxxxxxx
321...
2SheetWindow::SheetWindow(QWidget *parent)
3 : QMainWindow(parent)
4 ...
5 , m_model(new QStandardItemModel(100, 100, this))
6 , m_selection(new QItemSelectionModel(m_model))
7 ...
8{
9 ...
10 ui->m_table->setModel(m_model);
11 ui->m_table->setSelectionModel(m_selection);
12 ...
13 connect(m_selection, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
14 this,SLOT(on_m_selection_currentChanged(QModelIndex, QModelIndex)));
15 ...
16}
17...
18void SheetWindow::on_m_selection_currentChanged(
19 QModelIndex const& current, QModelIndex const& previous)
20{
21 Q_UNUSED(previous)
22
23 if (!current.isValid())
24 return;
25
26 m_labCellPos->setText(QString("单元格位置:第%1行,第%2列")
27 .arg(current.row() + 1).arg(current.column() + 1));
28
29 QStandardItem* item = m_model->itemFromIndex(current);
30 m_labCellText->setText(" 单元格内容:" + item->text());
31}
32...
运行效果如图所示: