1

Inspired by the following thread: PyQt: How to set Combobox Items be Checkable?
I was able to create a simple checkable "combobox" by using a QToolButton and adding checkable items to it using addAction. See simple code example:

from PyQt4 import QtCore, QtGui
import sys
class Ui_Dialog(object):
   def setupUi(self, Dialog):
       Dialog.setObjectName("Dialog")
       Dialog.resize(198, 157)
       self.toolButton = QtGui.QToolButton(Dialog)
       self.toolButton.setGeometry(QtCore.QRect(60, 50, 71, 19))
       self.toolButton.setObjectName("toolButton")
       self.toolButton.setText("MyButton")
       QtCore.QMetaObject.connectSlotsByName(Dialog)

class MyDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.toolMenu = QtGui.QMenu(self.ui.toolButton)
        for i in range(3):
            action = self.toolMenu.addAction("Category " + str(i))
            action.setCheckable(True)
        self.ui.toolButton.setMenu(self.toolMenu)
        self.ui.toolButton.setPopupMode(QtGui.QToolButton.InstantPopup)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyDialog()
    myapp.show()
    sys.exit(app.exec_())  

But how can I capture which of the QToolButton actions (i.e. Category 1 and/or Category 2/3) that has been checked in my dialog?

4

2 回答 2

1

或者,您可以定义您QActionGroup的收集所有actions,然后connect将信号发送triggered到回调方法,这样:

class MyDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.toolMenu = QtGui.QMenu(self.ui.toolButton)
        group = QtGui.QActionGroup(self.toolMenu)
        for i in range(3):
            action = self.toolMenu.addAction("Category %d" % i)
            action.setCheckable(True)
            action.setActionGroup(group)
            action.setData(i)
        self.ui.toolButton.setMenu(self.toolMenu)
        self.ui.toolButton.setPopupMode(QtGui.QToolButton.InstantPopup)
        group.triggered.connect(self.test)

    def test(self, act):
        print 'Action' , act.data().toInt()[0]

test()方法中,读取data每个action返回的 aQVariant您需要将其转换回int使用toInt返回(int, bool)元组的方法,因此[0]

于 2015-12-10T15:09:02.310 回答
0

首先我们需要遍历菜单的动作。没有方便的函数来做到这一点,但是每个小部件都有一个方法findChildren。要获取 type 的所有子项的列表QAction,请执行以下操作:

 self.toolMenu.findChildren(QtGui.QAction)

对于每个动作,我们都可以使用QAction.isChecked()来获取布尔值。

完整示例:

def whatIsChecked(self):
    for action in self.toolMenu.findChildren(QtGui.QAction):
        if action.isChecked():
            print(action.text(),"is checked")
        else:
            print(action.text(),"is not checked")
于 2015-12-09T12:37:01.257 回答