我为QTableView创建了一个工作的PushButton委托。按下按钮时,它将发出buttonClicked信号(并打印以显示它正在工作。
我已将按钮委托设置为第1列的项目委托(请参阅结尾附近的tableview.setItemDelegateForColumn(1,委托)。
我被困的地方是我想知道如何连接到pushButton发射信号。作为入门者,我可以遍历我的行/列并找到tableView中的每个元素(最后可以在示例中看到),所以我认为这可能是我可以建立连接的点。但是,我不知道该怎么做。可以在列级别完成吗?
任何帮助都将不胜感激。
# python 3.6
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import (QApplication, QStyleOptionButton, QTableView, QStyledItemDelegate, QStyle)
from PyQt5.QtCore import QModelIndex
class PushButtonDelegate(QStyledItemDelegate):
buttonClicked = QtCore.pyqtSignal(int, int)
def __init__(self, parent = None):
super().__init__(parent)
self._pressed = None
self._buttonTxt = 'Press Me'
def paint(self, painter, option, index):
painter.save()
opt = QStyleOptionButton()
opt.text = self._buttonTxt
opt.rect = option.rect
opt.palette = option.palette
if self._pressed and self._pressed == (index.row(), index.column()):
opt.state = QStyle.State_Enabled | QStyle.State_Sunken
else:
opt.state = QStyle.State_Enabled | QStyle.State_Raised
QtWidgets.QApplication.style().drawControl(QStyle.CE_PushButton, opt, painter)
painter.restore()
def editorEvent(self, event, model, option, index):
if event.type() == QtCore.QEvent.MouseButtonPress:
# store the position that is clicked
self._pressed = (index.row(), index.column())
return True
elif event.type() == QtCore.QEvent.MouseButtonRelease:
if self._pressed == (index.row(), index.column()):
print("Button pressed at {} {}".format(index.row(), index.column()))
self.buttonClicked.emit(*self._pressed)
self._pressed = None
return True
return False
def createEditor(self, parent, option, index):
""" Disable the createEditor or you'll lose your button on a double-click """
return None
def setEditorData(self, item, index):
""" We don't change what's in the button so disable this event also """
return None
def callBack_test(row, col):
print("CallbackTest called with {} {}".format(row, col))
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
rows = 4
cols = 2
delegate_col = 1
# Create an table view with a bunch of rows and columsn
model = QtGui.QStandardItemModel(rows, cols)
tableView = QTableView()
tableView.setWindowTitle("Pushbutton Delegate example")
tableView.setModel(model)
# We are setting column 1 to use the push button widget
delegate = PushButtonDelegate(None)
delegate.buttonClicked.connect(callBack_test) #<-- This is the answer
tableView.setItemDelegateForColumn(delegate_col, delegate)
# Now lets loop through our button delegates and connect to the signal?
for row in range(rows):
index = model.index(row, delegate_col, QModelIndex())
model.setData(index, 1)
# Is it possible to connect to the pushbutton signal here?
tableView.show()
sys.exit(app.exec_())
答案 0 :(得分:3)
一个代理实例会为所有列发出buttonClicked
信号,因此您只需执行以下操作:
delegate = PushButtonDelegate(None)
delegate.connect(slot)