#32 shortcuts fungerer nå ved flere TableModules i samme scene
Under følger en snippet som viser hva som ikke fungerte før:
from PySide2.QtWidgets import QVBoxLayout, QApplication, QWidget, QGraphicsScene, QGraphicsView, QTableWidget, QShortcut, QHBoxLayout
from PySide2.QtGui import QKeySequence
from PySide2.QtCore import Qt
class QTableWidthWithShortcuts(QTableWidget):
def __init__(self, *args, **kwargs):
super(QTableWidthWithShortcuts, self).__init__(*args, **kwargs)
shortcut = QShortcut(QKeySequence("Shift++"), self, context=Qt.WidgetWithChildrenShortcut)
shortcut.activated.connect(self.say_hello)
def say_hello(self):
print("Hello")
app = QApplication()
# inside QGrahpicsScene
# shortcuts don't work..
scene = QGraphicsScene()
view = QGraphicsView(scene)
t1 = QTableWidthWithShortcuts(2,2)
t1.move(0,0)
scene.addWidget(t1)
t2 = QTableWidthWithShortcuts(2,2)
t2.move(300,0)
scene.addWidget(t2)
view.show()
# inside QHBoxLayout
# shortcuts work!!
layout = QHBoxLayout()
t1 = QTableWidthWithShortcuts(2,2)
layout.addWidget(t1)
t2 = QTableWidthWithShortcuts(2,2)
layout.addWidget(t2)
wrapper_widget = QWidget()
wrapper_widget.setLayout(layout)
wrapper_widget.show()
app.exec_()
Her er en snippet som viser hvordan denne løsningen unngår problemet over:
from PySide2.QtWidgets import QVBoxLayout, QApplication, QWidget, QGraphicsScene, QGraphicsView, QTableWidget, QShortcut, QHBoxLayout
from PySide2.QtGui import QKeySequence
from PySide2.QtCore import Qt
class QTableWidthWithShortcuts(QTableWidget):
def __init__(self, uid, *args, **kwargs):
super(QTableWidthWithShortcuts, self).__init__(*args, **kwargs)
self.uid = uid
def keyPressEvent(self, event):
if event.key() == Qt.Key_Question:
print("{}: Shift and plus!".format(self.uid))
elif event.modifiers() == Qt.ShiftModifier and event.key() == Qt.Key_Underscore:
print("{}: Shift and minus!".format(self.uid))
elif event.modifiers() == Qt.ControlModifier and event.key() == Qt.Key_Plus:
print("{}: Ctrl and plus!".format(self.uid))
elif event.modifiers() == Qt.ControlModifier and event.key() == Qt.Key_Underscore:
print("{}: Ctrl and minus!".format(self.uid))
else:
super(QTableWidthWithShortcuts, self).keyPressEvent(event)
app = QApplication()
scene = QGraphicsScene()
view = QGraphicsView(scene)
t1 = QTableWidthWithShortcuts("A", 2,2)
t1.move(0,0)
scene.addWidget(t1)
t2 = QTableWidthWithShortcuts("B", 2,2)
t2.move(300,0)
scene.addWidget(t2)
view.show()
app.exec_()
Edited by Thomas Holene Løkkeborg