如何从QSlider获得价值

时间:2018-10-21 17:48:08

标签: python user-interface pyqt pyqt4 pyqt5

在此代码中,我想使用PyQt5创建QSlider的GUI。我想要的是在移动滑块时打印变化的值。但是在这里,它只打印90,这是滑块的主要值。

NB:我知道可以通过 valuechange 功能打印连续变化的值。但是我只需要通过 init 函数打印值。

代码:

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QCheckBox, QGridLayout,
QGroupBox,QMenu, QPushButton,
 QRadioButton, QVBoxLayout,
 QWidget, QSlider,QLabel)

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

      layout = QVBoxLayout()

      self.sl = QSlider(Qt.Horizontal)
      self.sl.setMinimum(0)
      self.sl.setMaximum(180)
      self.sl.setValue(90)
      self.sl.setTickPosition(QSlider.TicksBelow)
      self.sl.setTickInterval(10)

      layout.addWidget(self.sl)
      self.sl.valueChanged.connect(self.valuechange)
      self.setLayout(layout)
      self.setWindowTitle("slider")
      print(self.valuechange())

    def valuechange(self):
      self.size = self.sl.value()
      return self.size

def main():
   app = QApplication(sys.argv)
   ex = sliderdemo()
   ex.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   main()

1 个答案:

答案 0 :(得分:0)

如果您真的想要,可以:-)

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QCheckBox, QGridLayout,
                             QGroupBox,QMenu, QPushButton,
                             QRadioButton, QVBoxLayout,
                             QWidget, QSlider,QLabel)

class sliderdemo(QWidget):
    def __init__(self, vSl=90, parent=None):
        super(sliderdemo, self).__init__(parent)
        layout = QVBoxLayout()
        self.sl = QSlider(Qt.Horizontal)
        self.sl.setMinimum(0)
        self.sl.setMaximum(180)
        self.sl.setValue(vSl)
        self.sl.setTickPosition(QSlider.TicksBelow)
        self.sl.setTickInterval(10)

        layout.addWidget(self.sl)
        self.sl.valueChanged[int].connect(self.valuechange)
        self.setLayout(layout)
        self.setWindowTitle("slider")
        #print(self.valuechange())
        print("__init__vSl -> ", vSl)

    def valuechange(self, value):
        #self.size = self.sl.value()
        self.__init__(value)
        #return self.size

def main():
   app = QApplication(sys.argv)
   ex = sliderdemo(90)
   ex.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   main()

enter image description here