import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
"""
下面示例揭示了,当关键字绑定的控件出现的时候,快捷键才管用,
绑定的控件没有出现的时候快捷键无效
"""
class Demo1(QMainWindow):
def __init__(self):
super().__init__()
form_layout = QFormLayout()
self.text_edit = QTextEdit()
shortcut_show_msg = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_M), self.text_edit)
shortcut_show_msg.activated.connect(lambda: print('你好'))
button = QPushButton("显示/隐藏")
button.clicked.connect(self.show_or_hide)
form_layout.addRow("文本行", self.text_edit)
form_layout.addWidget(QTextEdit())
form_layout.addWidget(button)
widget = QWidget()
widget.setLayout(form_layout)
self.setCentralWidget(widget)
def show_or_hide(self):
if self.text_edit.isVisible():
self.text_edit.setVisible(False)
else:
self.text_edit.setVisible(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Demo1()
window.show()
sys.exit(app.exec_())