我想让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
答案 0 :(得分:1)
您必须使用QToolButton
并将checkable
属性设置为True,而不是使用QAction
:
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
答案 1 :(得分:-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)