Python qt: eventhandlers
From wikinotes
Events are generated when mouse buttons are clicked, keys are pressed, windows are selected etc.
You can rewrite, or create instances of these event handlers so that they behave exactly how you
want them to. Events mostly seem to be listed under the class QtGui.QWidget
Simple Example
class Example( QtGui.QDialog ):
def __init__(self): ## Build QDialog
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.show()
def keyPressEvent(self, e): ## Close Window if EscapeKey pushed
if e.key() == QtCore.Qt.Key_Escape:
self.close()
modifiers = QtWidgets.QApplication.keyboardModifiers()
if modifiers == QtCore.Qt.ShiftModifier:
if e.key() == QtCore.Qt.Key_T:
print('Shift + T pressed')
def leaveEvent(self, e): ## Close Window if becomes Unfocused
self.close()
Drag And Drop
class DropButton( QtGui.QPushButton ): ## Custom Button Class
""" Button Accepting Dragged Text """
def __init__(self, title, parent):
super(DropButton, self).__init__(title, parent)
self.setAcceptDrops(True) # Allow Drops to be Accepted
def dragEnterEvent(self, e): # Define dataTypes to accept
if e.mimeData().hasFormat('text/plain'): e.accept()
else: e.ignore()
def dropEvent(self, e): # Method to perform on drop
self.setText(e.mimeData().text()) # (ovewrite button label)
class Example( QtGui.QDialog ): ## Main Window
""" Main Window """
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
from PySide import QtCore, QtGui
from wpyside import newUI
self.setParent=newUI.getMaya()
qe = QtGui.QLineEdit( 'Drag Me to Btn', self ) # Text Field
qe.setDragEnabled(True) # (allow text to be dragged)
btn = DropButton( 'Button', self ) # custom button (above)
hl = QtGui.QHBoxLayout() # horizontalLayout
hl.addWidget(qe )
hl.addWidget(btn)
self.setLayout( hl )
self.show()