试试看:
#from PyQt4.QtCore import *
#from PyQt4.QtGui import *
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
# create objects
self.la = QLabel("Press Space or `w` in this box:")
self.le = MyLineEdit()
self.la2 = QLabel("\nLook here:")
self.le2 = QLineEdit()
self.btnSpace = QPushButton("Button1")
self.btnSpace.setEnabled(False)
self.btnSpace.clicked.connect(self.onBtnSpace)
self.btnW = QPushButton("Button2")
self.btnW.setEnabled(False)
self.btnW.clicked.connect(self.onBtnW)
# layout
layout = QVBoxLayout()
layout.addWidget(self.la)
layout.addWidget(self.le)
layout.addWidget(self.la2)
layout.addWidget(self.le2)
layout.addWidget(self.btnSpace)
layout.addWidget(self.btnW)
self.setLayout(layout)
# connections
#self.connect(self.le, SIGNAL("tabPressed"), self.update)
self.le.signalTabPressed[str].connect(self.update)
def update(self, keyPressed):
newtext = str(self.le2.text()) + str(keyPressed) #"tab pressed "
self.le2.setText(newtext)
if keyPressed == "Key Space; ":
self.btnSpace.setEnabled(True)
self.btnSpace.setText(str(keyPressed))
if keyPressed == "Key W; ":
self.btnW.setEnabled(True)
self.btnW.setText(str(keyPressed))
def onBtnSpace(self):
print("keyPressed -> btnSpace")
def onBtnW(self):
print("keyPressed -> btnW")
class MyLineEdit(QLineEdit):
signalTabPressed = pyqtSignal(str) # +++
def __init__(self, *args):
QLineEdit.__init__(self, *args)
def event(self, event):
#if (event.type()==QEvent.KeyPress) and (event.key()==Qt.Key_Tab):
if (event.type()==QEvent.KeyPress) and (event.key()==Qt.Key_Space):
self.signalTabPressed.emit("Key Space; ")
return True
if (event.type()==QEvent.KeyPress) and (event.key()==Qt.Key_W):
self.signalTabPressed.emit("Key W; ")
return True
return QLineEdit.event(self, event)
def main():
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()