Skip to main content
 首页 » 编程设计

python之QMenu 剥离的信号或事件

2024年11月24日9findumars

是否有信号/事件可用于 QMenu 撕下?

我有一个 QMenu 子类,其中有 .setTearOffEnabled(True),但如果用户点击可撕下的“栏”。

我无法使用 QtCore.Qt.WindowStaysOnTopHint,因为这会导致我的菜单已经处于撕裂状态。

例如:如果我的主工具区比撕下的大,我点击我的主工具,撕下的窗口就会在它后面。

请您参考如下方法:

在以下代码中,当按下撕下(虚线)时发出点击信号:

import sys 
from PyQt5 import QtCore, QtWidgets 
 
 
class Menu(QtWidgets.QMenu): 
    clicked = QtCore.pyqtSignal() 
 
    def mouseReleaseEvent(self, event): 
        if self.isTearOffEnabled(): 
            tearRect = QtCore.QRect( 
                0, 
                0, 
                self.width(), 
                self.style().pixelMetric( 
                    QtWidgets.QStyle.PM_MenuTearoffHeight, None, self 
                ), 
            ) 
            if tearRect.contains(event.pos()): 
                self.clicked.emit() 
                QtCore.QTimer.singleShot(0, self.after_clicked) 
        super(Menu, self).mouseReleaseEvent(event) 
 
    @QtCore.pyqtSlot() 
    def after_clicked(self): 
        tornPopup = None 
        for tl in QtWidgets.QApplication.topLevelWidgets(): 
            if tl.metaObject().className() == "QTornOffMenu": 
                tornPopup = tl 
                break 
        if tornPopup is not None: 
            print("This is the tornPopup: ", tornPopup) 
            tornPopup.setWindowFlag(QtCore.Qt.WindowStaysOnTopHint) 
 
 
if __name__ == "__main__": 
 
    app = QtWidgets.QApplication(sys.argv) 
    w = QtWidgets.QMainWindow(parent=None) 
    menu = Menu("Menu", tearOffEnabled=True) 
    menu.clicked.connect(lambda: print("clicked")) 
    w.menuBar().addMenu(menu) 
    for i in range(5): 
        action = QtWidgets.QAction("action{}".format(i), w) 
        menu.addAction(action) 
    w.show() 
    sys.exit(app.exec_())