QSlider手柄尺寸PyQt5

时间:2020-07-15 14:04:34

标签: python pyqt pyqt5 qtstylesheets qslider

我正在尝试增加Qslider手柄的宽度,以使其在小屏幕上更加用户友好,但是我只找到了用C ++做到这一点的方法。

我尝试使用以下代码在python中实现此功能,仅用于更改滑块的颜色:

<div class="container">
<div class="first"></div>
<div class="second">
  <img src="https://upload.wikimedia.org/wikipedia/commons/4/42/Shaqi_jrvej.jpg" alt="">
</div>
  </div>

有关如何正确使用QWidget.setStyleSheet()的任何建议。

2 个答案:

答案 0 :(得分:1)

可能的解决方案是使用QProxyStyle:

from PyQt5 import QtCore, QtWidgets


class SliderProxyStyle(QtWidgets.QProxyStyle):
    def pixelMetric(self, metric, option, widget):
        if metric == QtWidgets.QStyle.PM_SliderThickness:
            return 40
        elif metric == QtWidgets.QStyle.PM_SliderLength:
            return 40
        return super().pixelMetric(metric, option, widget)


class TestWindow(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal)

        style = SliderProxyStyle(self.slider.style())
        self.slider.setStyle(style)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.slider)
        lay.addStretch()


if __name__ == "__main__":

    import sys

    app = QtWidgets.QApplication(sys.argv)
    app.setStyle("fusion")
    w = TestWindow()
    w.show()
    app.exec_()

之前

enter image description here

之后

enter image description here

答案 1 :(得分:0)

可能的解决方案是使用QSS:

from PyQt5 import QtCore, QtWidgets


class TestWindow(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal)
        self.slider.setMinimumHeight(70)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.slider)
        lay.addStretch()


QSS = """
/* QSlider --------------------------------------  */
QSlider::groove:horizontal {
    border-radius: 1px;
    height: 3px;
    margin: 0px;
    background-color: rgb(52, 59, 72);
}
QSlider::groove:horizontal:hover {
    background-color: rgb(55, 62, 76);
}
QSlider::handle:horizontal {
    background-color: rgb(85, 170, 255);
    border: none;
    height: 40px;
    width: 40px;
    margin: -20px 0;
    border-radius: 20px;
    padding: -20px 0px;
}
QSlider::handle:horizontal:hover {
    background-color: rgb(155, 180, 255);
}
QSlider::handle:horizontal:pressed {
    background-color: rgb(65, 255, 195);
}
"""


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    app.setStyle("fusion")
    app.setStyleSheet(QSS)
    w = TestWindow()
    w.show()
    sys.exit(app.exec_())

enter image description here

相关问题