我需要一个简单的例子:如何连接 selectRow事件(如果在pyside中存在此事件)并调用相应的处理程序。例如
self.table_view.selectedRow.connect(lambda: self.handler(param))
答案 0 :(得分:3)
如果您使用的是QTableView,则需要连接到selectionChanged的selectionModel信号。然后,您可以使用选择模型的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_())
答案 1 :(得分:0)
谢谢你#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_())