pyqt QToolBar 选中高亮

目录

效果图

示例代码


效果图

示例代码

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_()

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI视觉网奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值