【问题标题】:Same style for QPushButton and QToolButton during mouse-over鼠标悬停期间 QPushButton 和 QToolButton 的样式相同
【发布时间】:2015-06-01 08:00:00
【问题描述】:

是否可以让 QPushButton 和 QToolButton 在鼠标悬停期间看起来相同,即悬停事件的外观和感觉?

我不使用自定义样式表,但有一个全局应用程序设置:

QtGui.QApplication.setStyle("plastique")

我正在寻找类似于将 QPushButton 的当前(系统默认)鼠标悬停样式表“传播”到 QToolButton 的东西。默认情况下,QPushButton 会在鼠标悬停时高亮显示,而 QToolButton 什么都不做。

环境:Qt 4.8.6,在 Linux CentOS 6 和 Windows 7 上运行

【问题讨论】:

  • 所以基本上你说你只是想禁用QPushButton上的悬停效果,这实际上与QToolButton无关吧?
  • 不,我想启用 QToolbutton 上的悬停效果(看起来像 QPushbutton)。
  • 最简单的方法是创建一个自定义样式表,为两个按钮提供相似的样式。系统风格的行为往往是内嵌的,并且在没有 API 调用时不容易被操纵。

标签: qt hover styles qpushbutton qtoolbutton


【解决方案1】:

以 Nicolas 的回答为出发点,我创建了自己的 CSS 样式表:

QPushButton,QToolButton {

  background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #fdfbf7, stop: 1 #cfccc7);
  border-width: 1px;
  border-color: #8f8f91;
  border-style: solid;
  border-radius: 3px;
  padding: 4px;
  padding-left: 5px;
  padding-right: 5px;
}

QToolButton[popupMode="1"] {

  padding-right: 18px;
}

QToolButton::menu-button {

  border-width: 1px;
  border-color: #8f8f91;
  border-style: solid;
  border-top-right-radius: 3px;
  border-bottom-right-radius: 3px;
  /* 16px width + 2 * 1px for border = 18px allocated above */
  width: 16px;
}

QPushButton:hover,QToolButton:hover {

  border-top-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #b2afaa, stop: 0.5 #4847a1, stop: 1 #7e7cb6);
  border-radius: 1px;
  border-top-width: 3px;
  border-bottom-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #7e7cb6, stop: 0.5 #4847a1, stop: 1 #b2afaa);
  border-bottom-width: 3px;
  background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e4e0e1, stop: 1 #cfcbcd);
}

QPushButton:pressed,QToolButton:pressed {

  background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #cfcbcd, stop: 1 #e4e0e1);
  border-width: 1px;
  border-color: #8f8f91;
}

QPushButton:focus,QToolButton:focus {

  outline: none;
}

为了应用样式,我使用了以下 PyQT 代码 sn-p:

cssFile = os.path.join(self.installDir, "etc", "Buttons.css")
with open(cssFile, "r") as fh:
    cssStyleSheet = "".join(fh.readlines())

    for i in range(self.verticalLayout.count()):
        widget = self.verticalLayout.itemAt(i).widget()
        if isinstance(widget, QtGui.QPushButton) or isinstance(widget, QtGui.QToolButton):
            widget.setStyleSheet(cssStyleSheet)
        # Make Tool- and PushButton same height...
        if isinstance(widget, QtGui.QToolButton):
            widget.setMaximumHeight(self.firstPushButton.sizeHint().height())

如果应用程序背景颜色设置为“#ede9e3”,则生成的外观几乎与默认的“plastique”样式相同。

首先,我将样式表应用于所有工具按钮和按钮(即系统默认值)。但在此之后,对话框中的所有按钮都失去了默认宽度。所以我决定只将样式应用于垂直布局内的按钮,其中包含所有涉及的按钮。

【讨论】:

    猜你喜欢
    • 2015-02-14
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多