QToolButton单击显示弹出菜单,直到单击某处

时间:2019-01-31 20:02:53

标签: pyqt qmenu qtoolbutton

我有一个附加了QMenu的QToolButton,其中的选项是通过读取文件来填充的。

当前,我已经对其进行编码,以便在我第一次执行该工具时填充/创建选项卡。但是,我在QToolButton上遇到问题,我必须初始化.click()才能真正填充菜单项,然后才能迭代QMenu操作。

问题是,当我使用.click()时,菜单保持在弹出模式,并且在我单击屏幕上的鼠标之前不会创建选项卡。

尝试使用.animateClick(10),并且也遇到了同样的问题...

文件内容示例:

coke
water
tea

在这种情况下,如果我向文件中添加了一些新内容,我仍然可以单击按钮并从此处添加新选项。

class MyWin(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MyWin, self).__init__()
        self.ui_setup()
        self.populate_tabs_at_start()

    def ui_setup(self):
        central_widget = QtGui.QWidget()
        self.setCentralWidget(central_widget)
        vlay = QtGui.QVBoxLayout(central_widget)
        hlay = QtGui.QHBoxLayout()
        vlay.addLayout(hlay)
        vlay.addStretch()

        self.add_button = QtGui.QToolButton()
        self.tab_bar = QtGui.QTabBar(self)
        self.add_button.setIcon(QtGui.QIcon('add.png'))

        self.qmenu = QtGui.QMenu(self.add_button)
        self.add_button.setMenu(self.qmenu)
        self.add_button.setPopupMode(QtGui.QToolButton.InstantPopup)

        self.qmenu.aboutToShow.connect(self.set_menu)

        self.tab_bar.setTabButton(
            0,
            QtGui.QTabBar.ButtonPosition.RightSide,
            self.add_button
        )

        hlay.addWidget(self.add_button)
        hlay.addWidget(self.tab_bar)

    @QtCore.pyqtSlot()
    def set_menu(self):
        with open('/Desktop/item_file.txt') as f:
            menu_options = f.read().splitlines()
            self.qmenu.clear()
            for opt in menu_options:
                self.qmenu.addAction(opt, partial(self.set_new_tab, opt))

    def set_new_tab(self, opt):
        self.tab_bar.addTab(opt)

    def populate_tabs_at_start(self):
        # need to click on the button to derive the menu
        self.add_button.click()

        # The menu does pops up but it did not go away which I thought it will,
        # unless I perform a mouse-click somewhere within my screen
        #self.add_button.animateClick(10)

        # get the menu actions within self.qmenu
        menu_actions = self.qmenu.actions()
        for act in menu_actions:
            self.set_new_tab(act)

此外,是否有更好的方法来处理/创建标签,如我在populate_tabs_at_start()中所详细介绍的那样?

0 个答案:

没有答案
相关问题