在QTableView中检测行单元格中的按钮单击,可以通过以下步骤实现:
下面是一个示例代码:
from PyQt5.QtWidgets import QApplication, QTableView, QPushButton, QWidget, QVBoxLayout, QMessageBox, QMainWindow
from PyQt5.QtCore import Qt, QModelIndex, pyqtSignal, QAbstractTableModel, QVariant, QSize
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QIcon
from PyQt5.QtWidgets import QStyledItemDelegate
class ButtonDelegate(QStyledItemDelegate):
buttonClicked = pyqtSignal(int, int)
def __init__(self, parent=None):
super(ButtonDelegate, self).__init__(parent)
def createEditor(self, parent, option, index):
button = QPushButton(parent)
button.clicked.connect(lambda: self.buttonClicked.emit(index.row(), index.column()))
return button
def setEditorData(self, editor, index):
pass
def setModelData(self, editor, model, index):
pass
def updateEditorGeometry(self, editor, option, index):
editor.setGeometry(option.rect)
class MyTableModel(QAbstractTableModel):
def __init__(self, data, headers):
super(MyTableModel, self).__init__()
self._data = data
self._headers = headers
def rowCount(self, parent=QModelIndex()):
return len(self._data)
def columnCount(self, parent=QModelIndex()):
return len(self._headers)
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return QVariant()
elif role == Qt.DisplayRole:
return self._data[index.row()][index.column()]
return QVariant()
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole and orientation == Qt.Horizontal:
return self._headers[section]
return QVariant()
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.table_view = QTableView()
self.setCentralWidget(self.table_view)
data = [
['John', 'Doe', 'Edit'],
['Jane', 'Smith', 'Edit'],
['Bob', 'Johnson', 'Edit']
]
headers = ['First Name', 'Last Name', 'Action']
model = MyTableModel(data, headers)
self.table_view.setModel(model)
delegate = ButtonDelegate(self.table_view)
delegate.buttonClicked.connect(self.handleButtonClicked)
self.table_view.setItemDelegateForColumn(2, delegate)
def handleButtonClicked(self, row, column):
QMessageBox.information(self, 'Button Clicked', f'Button clicked at row {row}, column {column}')
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
在上述示例代码中,我们创建了一个自定义的按钮委托类ButtonDelegate,用于在QTableView中显示按钮。在MainWindow类中,我们连接了按钮委托类的buttonClicked信号到handleButtonClicked槽函数,用于处理按钮点击事件。当按钮被点击时,会弹出一个消息框显示按钮所在的行和列。
这个示例中使用了PyQt5库来实现,你可以根据自己的需求选择其他的GUI库。
领取专属 10元无门槛券
手把手带您无忧上云