如何选择QTableView中的单元格,如QTextEdit中的字符?

时间:2015-04-24 19:17:36

标签: qt

我想使用QTableView构建一个类似十六进制编辑器的视图。每个单元格将表示一个字节的数据。如何配置QTableView选择行为,使其像典型的文本编辑控件一样?也就是说,不是选择矩形区域的单元格,而是选择一条线上的剩余单元格,任何中间线条的全部内容以及最后一条线条上的部分内容。

以图表形式(x被选中,.未被选中),我想要这样:

..................
......xxxxxxxxxxxx
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxx......
..................

想要这个:

..................
......xxxxxx......
......xxxxxx......
......xxxxxx......
......xxxxxx......
..................

2 个答案:

答案 0 :(得分:2)

最终,我成功地通过对QItemSelectionModel进行子类化并覆盖select方法来更改class RollingItemSelectionModel(QItemSelectionModel): def qindex2index(self, index): """ convert QModelIndex to offset into buffer """ m = self.model() return (m.columnCount() * index.row()) + index.column() def index2qindex(self, index): """ convert offset into buffer into QModelIndex """ m = self.model() r = index // m.columnCount() c = index % m.columnCount() return m.index(r, c) def select(self, selection, selectionFlags): # PyQt5 doesn't have method overloading, so we type switch if isinstance(selection, QItemSelection): # This is the overload with the QItemSelection passed to arg 0 qindexes = selection.indexes() indices = [] for qindex in qindexes: indices.append(self.qindex2index(qindex)) if indices: low = min(indices) high = max(indices) selection = QItemSelection() for i in xrange(low, high): qi = self.index2qindex(i) # inefficient, but functional # manually add all the bytes to select, one-by-one selection.select(qi, qi) elif isinstance(selection, QModelIndex): # This is the overload with the QModelIndex passed to arg 0 # since it's a single index, already works as expected. pass else: # Just in case raise RuntimeError("Unexpected type for arg 0: '%s'" % type(selection)) # Fall through. Select as normal super(RollingItemSelectionModel, self).select(selection, SelectionFlags) 的默认行为,如下所述:https://stackoverflow.com/a/10920294/87207

这是我的代码的关键部分:

pointX = transform.localPosition.x + transform.InverseTransformPoint(hit.point).x;

答案 1 :(得分:0)

我认为你可以为此目的使用QItemSelection / QItemSelectionRange类。

创建新的项目选择模型:

QItemSelectionModel::select( ... )

然后将其传递给视图:

QAbstractItemView::setSelectionModel( ... )