PySide(或 PyQt)信号和插槽基础知识 [英] PySide (or PyQt) signals and slots basics

查看:39
本文介绍了PySide(或 PyQt)信号和插槽基础知识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这样一个简单的例子,它使用信号和插槽连接两个滑块:

Consider a simple example like this which links two sliders using signals and slots:

from PySide.QtCore import *
from PySide.QtGui import *
import sys

class MyMainWindow(QWidget):
 def __init__(self):
  QWidget.__init__(self, None)

  vbox = QVBoxLayout()

  sone = QSlider(Qt.Horizontal)
  vbox.addWidget(sone)

  stwo = QSlider(Qt.Horizontal)
  vbox.addWidget(stwo)

  sone.valueChanged.connect(stwo.setValue)

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

您将如何更改此设置,以便第二个滑块与第一个滑块的移动方向相反?滑块 1 将使用以下值进行初始化:

How would you change this so that the second slider moves in the opposite direction as the first? Slider one would be initialized with these values:

  sone.setRange(0,99)
  sone.setValue(0)

滑块二将使用这些值进行初始化:

And slider two would be initialized with these values:

  stwo.setRange(0,99)
  stwo.setValue(99)

然后 stwo 的值将是 99 - sone.sliderPosition.

And then the value of stwo would be 99 - sone.sliderPosition.

您将如何实现信号和槽以使其工作?我希望有一个基于上述简单示例的工作示例.

How would you implement the signal and slot to make this work? I would appreciate a working example that builds on the simple example above.

推荐答案

你的例子有点坏,因为你忘记设置布局的父级,并且还把滑块小部件保存为成员属性以供以后访问... 但是要回答你的问题,它真的就像将你的连接指向你自己的函数一样简单:

Your example is a bit broken, because you forgot to set the parent of the layout, and also to save the slider widgets as member attributes to be accessed later... But to answer your question, its really as simple as just pointing your connection to your own function:

class MyMainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self, None)

        vbox = QVBoxLayout(self)

        self.sone = QSlider(Qt.Horizontal)
        self.sone.setRange(0,99)
        self.sone.setValue(0)
        vbox.addWidget(self.sone)

        self.stwo = QSlider(Qt.Horizontal)
        self.stwo.setRange(0,99)
        self.stwo.setValue(99)
        vbox.addWidget(self.stwo)

        self.sone.valueChanged.connect(self.sliderChanged)

    def sliderChanged(self, val):
        self.stwo.setValue(self.stwo.maximum() - val)

注意 sliderChanged() 如何与原始 setValue() 插槽具有相同的签名.您不是将一个小部件直接连接到另一个小部件,而是将其连接到自定义方法,然后将值转换为您想要的值,然后按照您想要的方式操作(在 stwo 上设置自定义值)

Note how sliderChanged() has the same signature as the original setValue() slot. Instead of connecting one widget directly to the other, you connect it to a custom method and then transform the value to what you want, and act how you want (setting a custom value on stwo)

这篇关于PySide(或 PyQt)信号和插槽基础知识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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