1

我想让 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()

我有两个工具栏。我打算使用cursorPositionChanged来执行此操作,但 PyQt 中仍有办法执行此操作 在此处输入图像描述

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

4

2 回答 2

5

而不是使用,QAction您必须使用QToolButton并将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 
于 2017-08-05T04:31:41.630 回答
-1

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

# 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)
于 2020-12-11T08:07:37.847 回答