QSlider和Key Press活动

时间:2012-11-26 22:32:15

标签: python pyqt signals qslider

我目前有一个QSlider,可以使用鼠标滚动图像数据帧。我希望能够使用箭头键滚动单步(一帧)。

这是我当前的sliderMoved代码:

def sliderMoved(self,val):
    """
    retrieves the data array for the index value specified by the slider
    """

    if self.fileheader is None:
        print "[DEBUG] change_image_index(): self.fileheader is None"
        return

    idx=val
    self.x=idx
    frame=self.fileheader.frameAtIndex(idx)
    image=scipy.ndimage.filters.maximum_filter(frame.data, size=5)

    self.image.setImage(image, scale=((10.28/512),(2.486/96)))
    print self.image.imageItem.pixelSize()

    def keyPressEvent(self, event):
        if event.key()==Qt.Key_Right:
            frame=self.fileheader.frameAtIndex(idx+1)

要将滑块连接到事件,我只需使用:

self.slider.sliderMoved.connect(self.sliderMoved)
self.slider.sliderMoved.connect(self.keyPressEvent)

箭头键移动滑块,但它不会导致图像跳过帧...我知道我在这里遗漏了一些傻事......

1 个答案:

答案 0 :(得分:6)

尝试连接滑块的valueChanged而不是sliderMoved

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

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.v_layout = QVBoxLayout()

        self.slider = QSlider()
        self.slider.setOrientation(Qt.Horizontal)
        self.label = QLabel('Slider at position 0')

        self.v_layout.addWidget(self.label)
        self.v_layout.addWidget(self.slider)

        self.setLayout(self.v_layout)

        self.slider.valueChanged.connect(self.slider_moved)

    def keyPressEvent(self, event):
        if event.key()==Qt.Key_Right:
            self.slider.setValue(self.slider.value() + 1)
        elif event.key()==Qt.Key_Left:
            self.slider.setValue(self.slider.value() - 1)
        else:
            QWidget.keyPressEvent(self, event)

    def slider_moved(self, position):
        self.label.setText('Slider at position %d' % position)


if __name__ == '__main__':
  app = QApplication(sys.argv)

  widget = Widget()
  widget.show()

  sys.exit(app.exec_())

从您的keyPressEvent,您只需更改滑块的值,这将导致连接到valueChanged的任何功能运行。