目录
效果图
示例代码
效果图
示例代码
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, QToolBar, QToolButtonclass HighlightingToolButton(QToolButton):def __init__(self, parent=None):super().__init__(parent)self.setCheckable(True)def nextCheckState(self):passclass 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 toolButtondef 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_()