Qt标准键在Python中停止工作

2024-06-01 10:51:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用

  • Linux薄荷19
  • Python版本:3.6.6
  • Qt版本:5.9.5
  • PyQt版本:5.10.1
  • SIP版本:4.19.7

我刚刚注意到用于关闭(CTRL+W)的标准短键已经停止工作。你知道吗

在我的文件中,我写了下面一行将其连接到关闭按钮

self.closeBtn.setShortcut(QtGui.QKeySequence(QtGui.QKeySequence.Close))

但如果我按下按钮什么也不会发生。如果我把它改成

self.closeBtn.setShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_W))

它按预期工作。 我也试过

self.closeBtn.setShortcut(QtGui.QKeySequence(QtGui.QKeySequence.Quit)) 

但是CTRL+Q也不起作用。标准钥匙适用于其他应用。 你知道为什么会这样吗?你知道吗


Tags: self版本标准linuxqt按钮pyqtctrl
2条回答
import sys
from PyQt5.QtGui     import *
from PyQt5.QtCore    import *
from PyQt5.QtWidgets import *

class demo_widget(QWidget):
    def __init__(self,parent=None):
        super().__init__(parent)
        lay_content = QVBoxLayout()
        self.closeBtn = QPushButton("Close")
        self.lineEdit = QLineEdit()

        self.closeBtn.clicked.connect(self.slt_close)
        self.closeAction = QAction(self, triggered=self.slt_close)
        self.closeAction.setShortcuts([QKeySequence("Ctrl+Q"), QKeySequence("Ctrl+W")])
        self.closeBtn.addAction(self.closeAction)

        lay_content.addWidget(self.closeBtn)
        lay_content.addWidget(self.lineEdit)
        self.setLayout(lay_content)

    def slt_close(self):
        self.lineEdit.setText("close")

if __name__ == '__main__':
    app=QApplication([])
    demo = demo_widget()
    demo.show()
    app.exec_()

enum QKeySequence::StandardKey

This enum represent standard key bindings. They can be used to assign platform dependent keyboard shortcuts to a QAction.

http://doc.qt.io/qt-5/qkeysequence.html#StandardKey-enum

试试看:

import sys
from PyQt5.QtGui     import *
from PyQt5.QtCore    import *
from PyQt5.QtWidgets import *

class MyButton(QMainWindow):              
    def __init__(self,parent=None):
        super().__init__(parent)

        btn1 = QPushButton("Click or `Ctrl+Q`", clicked=self.close)
        btn1.setShortcut(QKeySequence("Ctrl+Q"))

        btn2    = QPushButton("QKeySequence.Close", 
                              clicked=lambda: print("\n Please Press -> Ctrl+W"))
        quitAct = QAction("Close", btn2, triggered=self.close)
        quitAct.setShortcuts(QKeySequence.Close)                     # <<<=======
        btn2.addAction(quitAct)

        btn3 = QPushButton("Click or `Ctrl+P`", clicked=lambda: print("Hello Kajsa"))
        btn3.setShortcut(QKeySequence("Ctrl+P"))

        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)        
        v_layout = QVBoxLayout(centralWidget)
        v_layout.addWidget(btn1)
        v_layout.addWidget(btn2)
        v_layout.addWidget(btn3)

if __name__ == '__main__':
    app=QApplication([])
    mb = MyButton()
    mb.show()
    app.exec_()

enter image description here

相关问题 更多 >