【问题标题】:How can I set the initial index for Shift + click selection in Qt QTableView?如何在 Qt QTableView 中设置 Shift + 单击选择的初始索引?
【发布时间】:2021-09-27 12:22:13
【问题描述】:

我的问题是在 Ctrl + 单击后取消选择一个项目。它成为了下面 Shift + click select 的初始索引。

我希望将 Shift 选择的初始索引设置为索引 0。

例如:

#include <QApplication>
#include <QtWidgets>


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QStringListModel model({"1", "2", "3", "4", "5", "6", "7", "8", "9"});
    QTableView view;
    view.horizontalHeader()->setVisible(false);
    view.setSelectionBehavior(QAbstractItemView::SelectRows);
    view.setSelectionMode(QAbstractItemView::ExtendedSelection);
    view.setModel(&model);
    view.show();

    return a.exec();
}
  1. 选择行标题 2

  2. 使用 Ctrl + 单击取消选择行标题 2

  3. Shift + 单击行标题 5

预期结果: 已选择第 1、2、3、4 和 5 行。

实际结果: 已选择第 2、3、4 和 5 行。

有什么方法可以产生预期的结果?

【问题讨论】:

    标签: c++ qt qtableview


    【解决方案1】:

    为此,您应该将QTableView 子类化。这是针对 Qt4 测试的小示例。对于 Qt5,它应该非常相似。 标题:

    #ifndef CUSTOMTABLEWIDGET_H
    #define CUSTOMTABLEWIDGET_H
    
    #include <QTableView>
    
    class CustomTableWidget : public QTableView
    {
        Q_OBJECT
    public:
        explicit CustomTableWidget(QWidget *parent = 0);
    
    protected:
        void mousePressEvent(QMouseEvent *event);
    };
    
    #endif // CUSTOMTABLEWIDGET_H
    

    Cpp:

    #include "customtablewidget.h"
    
    #include <QMouseEvent>
    #include <QItemSelectionModel>
    
    CustomTableWidget::CustomTableWidget(QWidget *parent) :
        QTableView(parent)
    {
    }
    
    void CustomTableWidget::mousePressEvent(QMouseEvent *event)
    {
        QModelIndex clickedIndex = this->indexAt(QPoint(event->x(), event->y()));
    
        bool isShiftClicked = Qt::LeftButton == event->button() && (event->modifiers() & Qt::ShiftModifier);
        if (clickedIndex.isValid() && isShiftClicked)
        {
            bool isRowSelected = this->selectionModel()->isRowSelected(clickedIndex.row(),
                                                                       clickedIndex.parent());
            if (!isRowSelected)
            {
                QModelIndex initialIndex = this->model()->index(0, 0);
                this->selectionModel()->clear();
                this->selectionModel()->select(QItemSelection(initialIndex, clickedIndex),
                                               QItemSelectionModel::Select);
                event->accept();
                return;
            }
        }
    
        QTableView::mousePressEvent(event);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2015-08-12
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多