需要继承QObject
必须是QObject的子类
class WarehousePage : public QWidget
{
protected:
//实现事件过滤器函数
virtual bool eventFilter(QObject *watched, QEvent *event);
};
注册事件过滤器
这段代码表示WarehousePage类监控ui->tableView的所有事件
ui->tableView->installEventFilter(this);
实现eventFilter函数
bool WarehousePage::eventFilter(QObject *watched, QEvent *event)
{
if(watched == ui->tableView)//判断事件对象是否为ui->tableView
{
if(event->type() == QEvent::KeyRelease)//判断是否为回车键按下,不能用QEvent::KeyPress,不然会在表格数据更新之前触发
{
QKeyEvent *key = static_cast<QKeyEvent*>(event);//把事件对象转为QKeyEvent,因为前面已经判断是键盘事件
if(key->key() == Qt::Key_Enter || key->key() == Qt::Key_Return)//如果按键是回车键或小键盘的回车键
{
QModelIndexList modelIndexList = ui->tableView->selectionModel()->selectedIndexes();//获取当前选中的表格项
if(modelIndexList.count()>0)//是否有选中的表格
{
QModelIndex modelIndex = modelIndexList.at(0);//获取选中当中的第一个
int cRow = modelIndex.row();
int cColumn = modelIndex.column();
double height = m_model->item(cRow, 1)->text().toDouble();//获取表格的数据
double deep = m_model->item(cRow, 2)->text().toDouble();//获取表格的数据
}
return true;//返回true,表示事件已经处理,不再下发
}
return false;
}
return false;
}
return QWidget::eventFilter(watched, event);//其它事件,调用父类的eventFilter函数
}