带图标的 QSlider [英] QSlider with icons

查看:54
本文介绍了带图标的 QSlider的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一组图像,我想移动一个 QSlider 以便每一步都在它的正上方显示一个代表其中一个图像的小缩略图图标.有什么提示或建议吗?

Given a set of images, I'd like to move a QSlider such that every step shows a little thumbnail icon just above it representing one of the images. Any tips or suggestions?

推荐答案

你必须使用 QLabel 来显示图标和 QSlider 的 valueChanged 信号才能使图标改变.

You have to use a QLabel to show the icon and the valueChanged signal of QSlider to make the icon change.

import sys

from PyQt4.QtCore import pyqtSlot, Qt
from PyQt4.QtGui import QWidget, QVBoxLayout, QLabel, QSlider, QApplication, QPixmap


class Widget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.list_icons = ["icon1.png", "icon2.png", "icon3.png", "icon4.png", "icon5.png", "icon6.png"]

        lay = QVBoxLayout(self)
        self.label = QLabel()
        self.label.setAlignment(Qt.AlignHCenter)
        slider = QSlider(Qt.Horizontal)
        lay.addWidget(self.label)
        lay.addWidget(slider)
        slider.setMaximum(len(self.list_icons)-1)
        slider.valueChanged.connect(self.on_change_value)
        self.on_change_value(0)

    @pyqtSlot(int)
    def on_change_value(self, value):
        icon = self.list_icons[value]
        self.label.setPixmap(QPixmap(icon))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

<小时>

更新:

不需要计算位置,只需要使用 Qt 样式表即可.

It is not necessary to calculate the position, you should only use Qt Style Sheet.

import sys

from PyQt4.QtCore import pyqtSlot, Qt
from PyQt4.QtGui import QWidget, QVBoxLayout, QLabel, QSlider, QApplication, QPixmap


class IconSlider(QSlider):
    def __init__(self, icons, *args, **kwargs):
        QSlider.__init__(self, *args, **kwargs)
        self.icons = icons
        self.setMaximum(len(self.icons)-1)
        self.valueChanged.connect(self.on_change_value)
        self.on_change_value(0)

    @pyqtSlot(int)
    def on_change_value(self, value):
        icon = self.icons[value]
        self.setStyleSheet('''
                QSlider::handle:horizontal{{
                    image: url({});
                    margin: -4px 0;
                }}
            '''.format(icon))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = IconSlider(["icon1.png", "icon2.png", "icon3.png", "icon4.png", "icon5.png", "icon6.png"], Qt.Horizontal)
    w.show()
    sys.exit(app.exec_())

这篇关于带图标的 QSlider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆