PyQt如何使工具栏按钮显示为按下

PyQt how to make a toolbar button appeared as pressed

我想让 PyQt 工具栏中的特定按钮显示为已按下(蓝色背景)。假设当我点击工具栏按钮时,我希望它显示为已按下

import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Window(QtGui.QMainWindow):   
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 700, 700)
        self.setWindowTitle('Rich Text Editor')
        self.statusBar = QStatusBar()
        self.textEdit = QtGui.QTextEdit()
        self.setCentralWidget(self.textEdit)
        self.setStatusBar(self.statusBar)
        self.home()

    def home(self):
        changeBoldActionTB = \
        QtGui.QAction(QtGui.QIcon('bold-text-option.png'),
                      'Make the text bold', self)
        changeBoldActionTB.triggered.connect(self.changeBold)

        self.formatbar = QToolBar()
        self.addToolBar(Qt.TopToolBarArea, self.formatbar)
        self.formatbar.addAction(changeBoldActionTB)
        self.show()

    def changeBold(self):
         pass
         #I think this does't matter        

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()

我有两个 toolbars.I 正计划使用 cursorPositionChanged 来执行此操作,但在 PyQt 中仍然有办法执行此操作

可重现代码: https://files.fm/u/h4c2amdx

而不是使用 QAction 你必须使用 QToolButton and set the checkable 属性 到 True:

toolButton.setCheckable(True)

示例:

class Window(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.setWindowTitle('Rich Text Editor')
        self.statusBar = QStatusBar(self)
        self.textEdit = QtGui.QTextEdit(self)
        self.setCentralWidget(self.textEdit)
        self.setStatusBar(self.statusBar)

        self.home()

    def home(self):
        toolButton = QToolButton(self)
        toolButton.setIcon(QtGui.QIcon('bold-text-option.png'))
        toolButton.setCheckable(True)
        toolButton.toggled.connect(self.onToggled)

        self.formatbar = QToolBar(self)
        self.addToolBar(Qt.TopToolBarArea, self.formatbar)
        self.formatbar.addWidget(toolButton)

    def onToggled(self, checked):
        print(checked)

截图:

加号:要手动设置值并获取状态,请使用以下指令:

toolButton.setChecked(True) # set State
print(toolButton.isChecked()) # get State
toolButton.toggle() # change state 

动作也有一个可检查的标志,它们可以作为一个切换开关。对不起,我不懂英语。所以我用代码展示了它。

# add this code before self.formatbar = QToolBar()
# and create img file blue_bold-text-option.png
self.changeBoldActionTB.setCheckable(True)
icon = QIcon()
icon.addFile('bold-text-option.png', QSize(), QIcon.Normal, QIcon.Off)
icon.addFile('blue_bold-text-option.png', QSize(), QIcon.Normal, QIcon.On)
self.changeBoldActionTB.setIcon(icon)