我有一个QTableView
,我希望用户能够选择整行而不是单个单元格。所以我改变了选择行为,如下所示。
table->setSelectionBehavior(QAbstractItemView::SelectRows)
但现在当单击Tab键时,它仍会遍历单个单元格而不是整行。我希望用户能够遍历每一行而不是单个单元格。
答案 0 :(得分:3)
您必须从QTableView
类继承并覆盖keyPressEvent()
。例如:
#include <QTableView>
#include <QKeyEvent>
class CustomView : public QTableView
{
Q_OBJECT
// QWidget interface
protected:
void keyPressEvent(QKeyEvent *event) {
switch(event->key()) {
case Qt::Key_Tab: {
if(currentIndex().row() != model()->rowCount())
selectRow(currentIndex().row() + 1);
break;
}
default: QTableView::keyPressEvent(event);
}
}
public:
explicit CustomView(QWidget *parent = 0);
~CustomView(){}
signals:
public slots:
};
答案 1 :(得分:0)
作为子类QTableView
的替代方法,可以在其上安装事件过滤器。例如,这里我使用程序的MainWindow来过滤表视图中的事件,该表视图是窗口的子窗口小部件之一:
在mainwindow.h中:
class MainWindow: public QMainWindow {
private:
bool eventFilter(QObject *watched, QEvent *event) override;
}
在mainwindow.cpp中:
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if (watched == ui->tableView &&
event->type() == QEvent::KeyPress &&
static_cast<QKeyEvent*>(event)->key() == Qt::Key_Tab)
{
//Handle the tab press here
return true; //return true to skip further event handling
}
//If the event was not a tab press on the tableView, let any other handlers do their thing:
return false;
}
然后,在MainWindow::MainWindow()
(或任何位置)中安装事件过滤器,如下所示:
ui->tableView->installEventFilter(this);