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

Bur*_*sif 1 python pyqt pyqt4 qtoolbar

我想让 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()
Run Code Online (Sandbox Code Playgroud)

我有两个工具栏。我打算使用cursorPositionChanged来做到这一点,但在 PyQt 中仍然有办法做到这一点 在此处输入图片说明

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

eyl*_*esc 5

QAction您必须使用QToolButton并将checkable属性设置为 True,而不是使用:

toolButton.setCheckable(True)
Run Code Online (Sandbox Code Playgroud)

例子:

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)
Run Code Online (Sandbox Code Playgroud)

截图:

在此处输入图片说明

在此处输入图片说明

另外:要手动设置值并获取状态,请使用以下说明:

toolButton.setChecked(True) # set State
print(toolButton.isChecked()) # get State
toolButton.toggle() # change state 
Run Code Online (Sandbox Code Playgroud)