【问题标题】:QTableView: When selecting cells, how do I make the first cell selected the current index?QTableView:选择单元格时,如何让第一个单元格选择当前索引?
【发布时间】:2011-03-30 07:04:25
【问题描述】:

我有一个继承 QTableView 的简单类,我想要以下行为:当用户选择几个单元格时,我希望将选择的第一个单元格设置为当前索引。

例如,如果我从 (0, 0) 到 (2, 2) 选择,当我开始输入时,文本将显示在 (0, 0),而不是 (2, 2),这似乎是默认值.

我已尝试使用以下内容覆盖 setSelection 函数:

void SampleTable::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command)
{
    if((command & QItemSelectionModel::Current) != 0)
    {
        QModelIndex curr = indexAt(rect.topLeft());
        selectionModel()->select(curr, QItemSelectionModel::Current);

        command ^= QItemSelectionModel::Current;
    }
    QTableView::setSelection(rect, command);
}

但无济于事。这似乎与鼠标事件有关,但我在源代码中无法完全定位问题,我希望无论如何有一个更简单的方法。

【问题讨论】:

    标签: c++ qt indexing selection qtableview


    【解决方案1】:

    你想达到什么目的?如果您希望用户仅编辑/选择单个单元格,请使用 setSelectionBehaviour 强制执行此操作。否则,您可以尝试 chinfoo 的想法,但请确保以用户能够理解的方式传达行为(即他能够看到他的编辑将更改第一个单元格/行)。

    【讨论】:

      【解决方案2】:

      我发现了问题以及如何解决它,但它并不漂亮。问题在于 QAbstractItemView 的鼠标移动事件。经过大量调试和搜索源代码后,我在 qabstractitemview.cpp 中找到了这个:

      void QAbstractItemView::mouseMoveEvent(QMouseEvent *event)
      ...
      if (index.isValid()
              && (index != d->selectionModel->currentIndex())
              && d->isIndexEnabled(index))
          d->selectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
      }
      

      我通过给我的类一个 QModelIndex 成员来修复它,该成员存储左上角 QModelIndex 的最后一个位置(在我的覆盖版本的 setSelection 中设置,如上所示),然后我用这个覆盖了 mouseMoveEvent:

      
      void SampleTable::mouseMoveEvent(QMouseEvent *event)
      {
          QTableView::mouseMoveEvent(event);
          if (state() == ExpandingState || state() == CollapsingState || state() == DraggingState || state() == EditingState)
                  return;
          if ((event->buttons() & Qt::LeftButton)) {
              if (m_topLeft.isValid())
              {
                  selectionModel()->setCurrentIndex(m_topLeft, QItemSelectionModel::NoUpdate);
              }
          }
      }
      
      不是一个很好的解决方案,但它有效。

      【讨论】:

        【解决方案3】:

        QtableWidget 类有一个信号 itemSelectionChanged(),将其连接到您的自定义插槽。在该槽中,使用selectedIndexes() 获取所有索引,然后使用setCurrentIndex() 设置您希望成为当前索引的单元格。

        【讨论】:

        • 我使用的是 QTableView,而不是 QTableWidget,所以信号不可用。
        猜你喜欢
        • 1970-01-01
        • 2012-01-13
        • 2023-01-25
        • 2010-10-21
        • 1970-01-01
        • 2014-07-17
        • 2018-06-14
        • 1970-01-01
        • 2023-03-06
        相关资源
        最近更新 更多