获取QTableView

时间:2015-10-01 10:39:33

标签: pyqt pyside qtableview

我正在尝试索引所选行,但是当我尝试

1。

indexes = tableview.selectionModel().selection().indexes()

索引将是所选行列总次数的列表,

即使我尝试 的 2

indexes = tableView.selectedIndexes()

这也给我选择了正确的索引,但总列数...

我只想在列表中选择一行。

1 个答案:

答案 0 :(得分:2)

如果您选择整个行,则可以通过更改窗口小部件的SelectionBehavior来执行此操作。这将自动选择整行,而不是单个单元格。

self.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)

设置完毕后,在'itemSelectionChanged'信号中,您需要打印每个项目的行:

def __init__(self):
    ...
    self.itemSelectionChanged.connect(self.selection_changed)

def selection_changed(self):
    rows=[idx.row() for idx in self.selectionModel().selectedRows()]
    print(rows)   # or return rows

对于看起来像这样的表(使用此选择),将返回以下内容

Example Table

显示以下选项:

[1, 2]

如果您不想使用SelectionBehavior选择每一列,则需要稍微更改信号。如果选择整个行,selectedRows将只返回一行。如果您正在选择单个单元格,但仍然只想要该行,请将您的信号更改为:

def selection_changed(self):
    rows=[idx.row() for idx in self.selectionModel().selectedIndexes()]
    rows = set(rows)
    print(rows)    # or return rows

这会将selectedRows更改为selectedIndexes。您注意到的重要一点是它将为所选的每个单元格返回一个条目,即使它们位于同一行。对此的解决方案是

rows = set(rows)

这将仅返回唯一条目。因此,与上面相同的选择返回

set([1,2])