Here is an example of how you can get a table cell’s text when clicking on it.
Suppose a QTableView defined in some MyClass class. You need to connect the clicked signal to your own MyClass::onTableClicked() slot, as shown below:
connect(tableView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(onTableClicked(const QModelIndex &)));
注意:QT的connect只寫參數類型,不寫參數名。
Slot implementation:
void MyClass::onTableClicked(const QModelIndex &index)
{
if (index.isValid()) {
QString cellText = index.data().toString();
}
}
You can use also doubleClicked, pressed or other signals depending on your goal.
在做一個Qt項目時遇到一個小問題,情況是這樣的,我初始化完一個table後,點擊裏面的單元格會產生一個事件,這次提醒了一次,在table中刪除了一行刷新這個table後,再次點擊單元格產生點擊事件2次,再刷新一次table,產生點擊事件3次,沒刷新一次點擊事件多重複1次,很是鬱悶。
經過分析,最後發現是connect函數的問題,解決辦法是:在每次刷新列表前解綁之前綁定的事件,這樣就不會重複產生點擊事件了。代碼如下:
//解綁,防止點擊QTableView單元格多次觸發
disconnect(ui->tableView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(onTableClicked(const QModelIndex &)));
......
//綁定,點擊QTableView單元格觸發
connect(ui->tableView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(onTableClicked(const QModelIndex &)));