gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 20:42:54 26 4
gpt4 key购买 nike

我想让 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 中仍然有办法做到这一点 enter image description here

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

最佳答案

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

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)

截图:

enter image description here

enter image description here

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

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

关于python - PyQt如何使工具栏按钮显示为按下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45511056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com