使用 Tab 键遍历 QTableView 行

Walk through QTableView rows using tab key

我有一个 QTableView,我希望用户能够 select 整行而不是单个单元格。所以我更改了 selection 行为,如下所示。

table->setSelectionBehavior(QAbstractItemView::SelectRows)

但现在当点击 Tab 键时,它仍然会遍历单个单元格而不是整行。我希望用户能够遍历每一行而不是单个单元格。

您必须继承 QTableView class 并覆盖 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:

};

作为子类化 QTableView 的替代方法,您可以在其上安装事件过滤器。例如,这里我使用程序的 MainWindow 来过滤 table 视图上的事件,该视图是 window 的子窗口小部件之一:

在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);