我需要一个简单的例子:如何连接 selectRow 事件(如果 pyside 中存在此事件)并调用相应的处理程序。例如
self.table_view.selectedRow.connect(lambda: self.handler(param))
如果您使用的是 QTableView,则需要连接到其 selectionModel 的 selectionChanged 信号。然后,您可以使用选择模型的 selectedRows 方法来获取所选行(其中“所选行”表示选择 整行)。
这是一个简单的演示:
from PySide import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self, rows, columns):
QtGui.QWidget.__init__(self)
self.table = QtGui.QTableView(self)
model = QtGui.QStandardItemModel(rows, columns, self.table)
for row in range(rows):
for column in range(columns):
item = QtGui.QStandardItem('(%d, %d)' % (row, column))
item.setTextAlignment(QtCore.Qt.AlignCenter)
model.setItem(row, column, item)
self.table.setModel(model)
selection = self.table.selectionModel()
selection.selectionChanged.connect(self.handleSelectionChanged)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.table)
def handleSelectionChanged(self, selected, deselected):
for index in self.table.selectionModel().selectedRows():
print('Row %d is selected' % index.row())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window(5, 5)
window.show()
window.setGeometry(600, 300, 600, 250)
sys.exit(app.exec_())
感谢#ekhumoro 的回答,这真的很有帮助。 我也尝试修改你的代码
#from PySide import QtGui, QtCore
from PyQt4 import QtGui, QtCore #
class Window(QtGui.QWidget):
def __init__(self, rows, columns):
QtGui.QWidget.__init__(self)
self.table = QtGui.QTableView(self)
self.table.setSelectionMode(QtGui.QTableView.SingleSelection) #
self.table.setSelectionBehavior(QtGui.QTableView.SelectRows) #
model = QtGui.QStandardItemModel(rows, columns, self.table)
for row in range(rows):
for column in range(columns):
item = QtGui.QStandardItem('(%d, %d)' % (row, column))
item.setTextAlignment(QtCore.Qt.AlignCenter)
model.setItem(row, column, item)
self.table.setModel(model)
# selection = self.table.selectionModel()
# selection.selectionChanged.connect(self.handleSelectionChanged)
self.table.selectionModel().currentRowChanged.connect(self.handleSelectionChanged)
self.assetChanged(self.table.currentIndex())
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.table)
#def handleSelectionChanged(self, selected, deselected):
# for index in self.table.selectionModel().selectedRows():
# print('Row %d is selected' % index.row())
def handleSelectionChanged(self, index): #
if index.isValid(): #
print('Row %d is selected' % index.row()) #
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window(5, 5)
window.show()
window.setGeometry(600, 300, 600, 250)
sys.exit(app.exec_())