目录
效果图
示例代码
效果图
示例代码
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, QToolBar, QToolButton
class HighlightingToolButton(QToolButton):
def __init__(self, parent=None):
super().__init__(parent)
self.setCheckable(True)
def nextCheckState(self):
pass
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Highlighting ToolButton Example")
self.resize(400, 300)
# 创建工具按钮并添加到工具栏
self.toolButton1 = self.add_tool_button("Action 1", self.on_action_triggered)
self.toolButton2 = self.add_tool_button("Action 2", self.on_action_triggered)
self.toolButton3 = self.add_tool_button("Action 3", self.on_action_triggered)
# 创建工具栏并添加工具按钮
toolbar = QToolBar("MyToolBar")
self.addToolBar(toolbar)
toolbar.addWidget(self.toolButton1)
toolbar.addWidget(self.toolButton2)
toolbar.addWidget(self.toolButton3)
# 设置样式表,使得在鼠标悬停或点击时高亮
self.setStyleSheet("QToolButton:checked { background-color: yellow; }")
def add_tool_button(self, text, triggered):
action = QAction(text, self)
action.triggered.connect(triggered)
toolButton = HighlightingToolButton()
toolButton.setDefaultAction(action)
toolButton.clicked.connect(self.on_tool_button_clicked)
return toolButton
def on_tool_button_clicked(self):
button = self.sender()
if button.isChecked():
for widget in self.findChildren(HighlightingToolButton):
if widget is not button:
widget.setChecked(False)
def on_action_triggered(self):
print("ToolButton triggered!")
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()