给定一组图像,我想移动一个QSlider
,这样每一步都会在其上方显示一个小缩略图图标,代表其中一个图像。有任何提示或建议吗?
答案 0 :(得分:2)
您必须使用QLabel显示QSlider的图标和valueChanged信号才能更改图标。
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样式表。
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_())