Exemplo n.º 1
0
class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.uiInit()

    def uiInit(self):
        self.value = 0

        self.dial = QDial(self)
        self.dial.move(0, 100)
        self.dial.setRange(0, 9999)
        self.dial.setNotchesVisible(True)
        self.lcd = QLCDNumber(self)

        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle('来来来')

        # self.dial.valueChanged.connect(self.lcd.display)

        self.show()

    def mousePressEvent(self, e):
        self.value += 1
        print(self.value)
        self.lcd.display(self.value)
    def createEditor(self, parent, option, index):
        editor = QDial(parent=parent)
        editor.setRange(-5, 5)
        editor.setNotchesVisible(True)
        editor.setAutoFillBackground(True)

        return editor
Exemplo n.º 3
0
class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    
    def initUI(self):
        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.move(30, 30) # 슬라이더 위치는 x축 30, y축 30 떨어진 곳에
        self.slider.setRange(0, 50) # 슬라이더 범위
        self.slider.setSingleStep(2) # 슬라이더는 하나로만 잡고(SingleStep) 2씩 증가!
        
        self.dial = QDial(self)
        self.dial.move(30, 50) # 슬라이더 보다 아래쪽에 위치 
        self.dial.setRange(0, 50) # 슬라이더와 동일한 범위

        btn = QPushButton('Default', self)
        btn.move(35, 160) 
        
        self.slider.valueChanged.connect(self.dial.setValue)
        # 슬라이더 쪽에 변화가 일어난 후, 다이얼값이 슬라이더와 동일하게 발생할 수 있도록!
        # => 슬라이더가 움직이면 다이얼도 움직이도록 하는 것!
        # valueChanged() : 슬라이더 값이 변할 때 발생!
        self.dial.valueChanged.connect(self.slider.setValue)
        btn.clicked.connect(self.button_clicked)
        
        self.setWindowTitle('QSlider and QDial')
        self.setGeometry(300, 300, 400, 200)
        self.show()
        
    def button_clicked(self):
        self.slider.setValue(0)
        self.dial.setValue(0) #버튼 누르면 초기화 시키려고 값을 0으로 줌!
Exemplo n.º 4
0
    def initUI(self):
        self.combo = QComboBox(self)
        self.combo.move(10, 10)
        self.combo.activated[str].connect(self.onActivated)

        refresh = QPushButton('Refresh', self)
        refresh.move(10, 40)
        refresh.clicked.connect(self.refreshClicked)

        # sld = QSlider(Qt.Horizontal, self)
        # sld.setFocusPolicy(Qt.NoFocus)
        # sld.setGeometry(30, 40, 150, 30)

        sld = QDial(self)
        sld.setRange(0, 360)
        sld.move(10, 70)
        sld.valueChanged[int].connect(self.changeValue)

        self.motorAngle = QLabel("Angle: 000", self)
        self.motorAngle.move(120, 110)

        self.status = QLabel("Select a COM", self)
        self.status.move(10, 180)

        self.setGeometry(200, 200, 200, 200)
        self.setWindowTitle('Motor Control')

        self.combo.addItem("Connect/Refresh")
        self.show()
        self.addPorts()

        self.positionGraph = AnalogPosition()
        self.positionGraph.show()
class MyMainWindow(QMainWindow):
    def __init__(self, ch=0, parent=None, name="Temperatur Simulation"):
        super().__init__(parent)
        self.setWindowTitle(name)
        self.__channel = ch

        cw = QWidget(self)
        layout = QVBoxLayout(cw)

        self.setCentralWidget(cw)
        self.__label = QLabel("Temperatur:        ", self)
        self.__dial = QDial(self)
        self.__dial.setRange(100, 400)
        self.__dial.setSingleStep(1)
        self.__dial.setPageStep(10)
        self.__dial.setTracking(False)

        layout.addWidget(QLabel("Channel: {}".format(ch), self))
        layout.addWidget(self.__label)
        layout.addWidget(self.__dial)
        self.__dial.valueChanged.connect(self.__sliderChanged)
        self.__dial.setValue(200)
        self.__sliderChanged()

    def __sliderChanged(self):
        temp = self.__dial.value() / 10
        self.__label.setText("Temperatur: {:.1f}°".format(temp))
        temp = temp * 4096.0 / 330
        with open('/tmp/wiringPiSPI_{}'.format(self.__channel), 'w') as f:
            fcntl.flock(f, fcntl.LOCK_EX)
            f.write("{} {} {}".format(6, int(temp // 256), int(temp % 256)))
            fcntl.flock(f, fcntl.LOCK_UN)
Exemplo n.º 6
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Volume Evaluation")
        self.setFixedSize(600, 400)
        self.Volume_Evaluation()
        self.dial()

    def dial(self):
        self.widget = QDial(self)
        self.widget.setGeometry(100, 100, 150, 200)  # x,y,w,h
        self.widget.setRange(0, 100)
        self.widget.setSingleStep(1)  # set keyboard input to 1 step
        self.widget.setSliderPosition(0)  # set pos to 0
        self.widget.valueChanged.connect(self.value_changed)

    def Volume_Evaluation(self):
        self.text_label = QLabel("Move Dial to Evaluate", self)
        self.text_label.setGeometry(260, 150, 320, 100)  # x,y,w,h
        self.text_label.setFont(QFont('Arial', 15))

    def value_changed(self, i):
        if i == 0: self.text_label.setText(f"Current value[{i}]: Muted")
        if i > 0: self.text_label.setText(f"Current value[{i}]: Very Low")
        if i >= 20: self.text_label.setText(f"Current value[{i}]: Low")
        if i >= 45: self.text_label.setText(f"Current value[{i}]: Medium")
        if i >= 80: self.text_label.setText(f"Current value[{i}]: High")
        if i == 100: self.text_label.setText(f"Current value[{i}]: Max")
        print(i)
Exemplo n.º 7
0
class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.slider = QSlider(Qt.Horizontal, self)
        #수평 슬라이더 생성, 생성시킬때 수평, 수직 설정. 상수는 Qt가 갖고있으니 임포트 해옴
        self.slider.move(30, 30)
        self.slider.setRange(0, 50)
        self.slider.setSingleStep(2)
        # 싱글스탭 으로 하고 간격은 2

        self.dial = QDial(self)  #다이얼 객체 생성
        self.dial.move(30, 50)
        self.dial.setRange(0, 50)  #다이얼 범위 지적

        btn = QPushButton('Default', self)
        btn.move(35, 160)

        self.slider.valueChanged.connect(
            self.dial.setValue)  #슬라이더 값 변화 일어난 후 다이얼 값도 동일하게(내장함수임)
        self.dial.valueChanged.connect(
            self.slider.setValue)  #다이얼의 값 변화가 일어난 후 슬라이더값도 동일하게(내장함수, 직접설정)
        btn.clicked.connect(self.button_clicked)

        self.setWindowTitle('QSlider and QDial')
        self.setGeometry(300, 300, 400, 200)
        self.show()

    def button_clicked(self):
        self.slider.setValue(0)
        self.dial.setValue(0)
Exemplo n.º 8
0
class MySliderDial(QGroupBox):

    def __init__(self):
        super().__init__()
        self.setTitle('QSlider & QDial')
        self.init_ui()

    def init_ui(self):
        # Qt.Horizontal, Qt.Vertical 수평 또는 수직 방향 설정
        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.setRange(0, 50)   # setRange() 메서드로 값의 범위를 0에서 50까지로 설정
        self.slider.setSingleStep(2)  # setSingleStep() 메서드는 조절 가능하는 최소 단위를 설정

        self.dial = QDial(self)
        self.dial.setRange(0, 50)

        btn = QPushButton('Default', self)

        # 슬라이더와 다이얼의 값이 변할 때 발생하는 시그널을 각각 다이얼과 슬라이더의 값을 조절해주는
        # 메서드 (setValue)에 서로 연결함으로써 두 위젯의 값이 언제나 일치하도록 해줍니다.
        self.slider.valueChanged.connect(self.dial.setValue)
        self.dial.valueChanged.connect(self.slider.setValue)

        btn.clicked.connect(self.button_clicked)

        layout = QVBoxLayout()
        layout.addWidget(self.slider)
        layout.addWidget(self.dial)
        layout.addWidget(btn)

        self.setLayout(layout)

    def button_clicked(self):
        self.slider.setValue(0)
        self.dial.setValue(0)
Exemplo n.º 9
0
class Demo(QWidget):
    def __init__(self):
        super(Demo, self).__init__()
        # setWindowTitle()方法可以设置窗口标题;
        self.setWindowTitle('QDial')  # 1

        self.dial = QDial(self)
        # 实例化一个QDial控件后,通过setFixedSize()方法来固定QDial的大小
        # 如果不设置该方法的话,我们会发现在改变表盘数值时,表盘的大小会发生改变;

        self.dial.setFixedSize(100, 100)  # 2
        # 使用setRange()方法来设置表盘数值范围,
        # 当然也可以使用setMinimum()和setMaximum()方法;
        self.dial.setRange(0, 100)  # 3
        # setNotchesVisible(True)可以显示刻度,刻度会根据我们设置的数值自动调整;
        self.dial.setNotchesVisible(True)  # 4
        # 当改变表盘数值时,会触发valueChanged信号,在槽函数中我们让QLabel显示出当前表盘数值。
        self.dial.valueChanged.connect(self.on_change_func)  # 5

        self.label = QLabel('0', self)
        self.label.setFont(QFont('Arial Black', 0))

        self.h_layout = QHBoxLayout()
        self.h_layout.addWidget(self.dial)
        self.h_layout.addWidget(self.label)

        self.setLayout(self.h_layout)

    def on_change_func(self):
        self.label.setText(str(self.dial.value()))
        self.label.setFont(QFont('Arial Black', (int(self.dial.value()) + 10)))
    def createEditor(self, parent, option, index):
        editor = QDial(parent=parent)
        editor.setRange(-5, 5)
        editor.setNotchesVisible(True)
        editor.setAutoFillBackground(True)

        return editor
class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        pass

    def initUI(self):
        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.move(30, 30)
        self.slider.setRange(0, 50)
        self.slider.setSingleStep(2)

        self.dial = QDial(self)
        self.dial.move(30, 50)
        self.dial.setRange(0, 50)

        button = QPushButton('Default', self)
        button.move(35, 160)

        self.slider.valueChanged.connect(self.dial.setValue)
        self.dial.valueChanged.connect(self.slider.setValue)
        button.clicked.connect(self.button_clicked)

        self.setWindowTitle('QSlider and QDial')
        self.setGeometry(300, 300, 400, 200)
        self.show()
        pass

    def button_clicked(self):
        self.slider.setValue(0)
        self.dial.setValue(0)
        pass

    pass
Exemplo n.º 12
0
Arquivo: dial.py Projeto: ara710/TMMT
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # 윈도우 설정
        self.setGeometry(200, 100, 300, 300)  # x, y, w, h
        self.setWindowTitle('삼인성호')

        # QSliter  추가
        self.dial = QDial(self)
        self.dial.move(10, 10)
        self.dial.setFixedSize(100, 100)
        self.dial.setRange(0, 100)
        self.dial.setMinimum(1)
        self.dial.setMaximum(24)
        self.dial.setNotchesVisible(True)
        self.dial.valueChanged.connect(self.value_changed)

        # QSlider 데이터를 표시할 라벨
        self.label = QLabel(self)
        self.label.setGeometry(10, 120, 200, 100)
        self.label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label.setStyleSheet("border-radius: 5px;"
                                 "border: 1px solid gray;"
                                 "background-color: #ffffff")

    # 슬라이드 시그널 valueChanged 연결 함수
    def value_changed(self, value):
        self.label.setText(str(value) + "시")
        self.label.setFont(QtGui.QFont("Malgun Gothic", 40))  #폰트,크기 조절
Exemplo n.º 13
0
    def initUI(self):
        self.combo = QComboBox(self)
        self.combo.move(10, 10)
        self.combo.activated[str].connect(self.onActivated)

        refresh = QPushButton("Refresh", self)
        refresh.move(10, 40)
        refresh.clicked.connect(self.refreshClicked)

        # sld = QSlider(Qt.Horizontal, self)
        # sld.setFocusPolicy(Qt.NoFocus)
        # sld.setGeometry(30, 40, 150, 30)

        sld = QDial(self)
        sld.setRange(0, 360)
        sld.move(10, 70)
        sld.valueChanged[int].connect(self.changeValue)

        self.motorAngle = QLabel("Angle: 000", self)
        self.motorAngle.move(120, 110)

        self.status = QLabel("Select a COM", self)
        self.status.move(10, 180)

        self.setGeometry(200, 200, 200, 200)
        self.setWindowTitle("Motor Control")

        self.combo.addItem("Connect/Refresh")
        self.show()
        self.addPorts()

        self.positionGraph = AnalogPosition()
        self.positionGraph.show()
Exemplo n.º 14
0
class PlaneSetter(QWidget):
    """
    Class for plane setter with dial, this update using setPlaneShift and
    incrementPlaneShift

    """
    def __init__(self,
                 scale=0.01,
                 parent=None,
                 closeAction=None,
                 changedAction=None):
        super(PlaneSetter, self).__init__(parent)

        self.closeAction = closeAction
        self.changedAction = changedAction
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.white)
        self.setPalette(p)

        self.shift = getPlaneShift()
        self.scale = scale

        self.planeLabel = QLabel("Plane : " + "{0:5.3f}".format(self.shift))
        self.planeDial = QDial()
        self.planeDial.setRange(-100, 100)
        self.planeDial.setValue(int(self.shift / self.scale))
        self.planeDial.valueChanged.connect(self.valueChange)
        closeButton = QPushButton("Close")
        closeButton.clicked.connect(self.closeButtonClicked)
        resetButton = QPushButton("Reset")
        resetButton.clicked.connect(self.resetButtonClicked)

        layout = QGridLayout()
        layout.addWidget(self.planeLabel, 0, 1)
        layout.addWidget(self.planeDial, 1, 0, 1, 2)
        layout.addWidget(resetButton, 2, 0)
        layout.addWidget(closeButton, 2, 1)
        self.setLayout(layout)

    def valueChange(self):
        global PlaneShift
        self.shift = self.planeDial.value() * self.scale
        self.planeLabel.setText("Plane : " + "{0:5.3f}".format(self.shift))
        setPlaneShift(self.shift)
        if self.changedAction != None:
            self.changedAction()

    def resetButtonClicked(self):
        self.shift = 0.0
        self.planeDial.setValue(0)
        self.valueChange()

    def closeButtonClicked(self):  # Close the frame
        self.close()
        if self.closeAction != None:
            self.closeAction()
Exemplo n.º 15
0
class IrisSetter(QWidget):
    """
    Class to set default direction in degress with spinners
    """
    def __init__(self, parent=None, closeAction=None):
        super(IrisSetter, self).__init__(parent)

        global IrisRatio

        self.closeAction = closeAction
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.white)
        self.setPalette(p)

        self.irisRatio = IrisRatio
        self.irisLabel = QLabel("Iris : " + str(self.irisRatio))
        self.irisDial = QDial()
        self.irisDial.setRange(0, 100)
        self.irisDial.setValue(int(100 * self.irisRatio))
        self.irisDial.valueChanged.connect(self.valueChange)
        closeButton = QPushButton("Close")
        closeButton.clicked.connect(self.closeButtonClicked)
        resetButton = QPushButton("Reset")
        resetButton.clicked.connect(self.resetButtonClicked)

        layout = QGridLayout()
        layout.addWidget(self.irisLabel, 0, 1)
        layout.addWidget(self.irisDial, 1, 0, 1, 2)
        layout.addWidget(resetButton, 2, 0)
        layout.addWidget(closeButton, 2, 1)
        self.setLayout(layout)

    def valueChange(self):
        global IrisRatio
        self.irisRatio = self.irisDial.value() / 100.0
        self.irisLabel.setText("Iris : " + str(self.irisRatio))
        IrisRatio = self.irisRatio
        getCurrentLens().setIris(self.irisRatio)

    def resetButtonClicked(self):
        self.iris = 1.0
        self.irisDial.setValue(100)
        self.valueChange()

    def closeButtonClicked(self):  # Close the frame
        self.close()
        if self.closeAction != None:
            self.closeAction()
Exemplo n.º 16
0
    def __init__(self):
        super().__init__()

        self.setWindowTitle("My App")

        widget = QDial()
        widget.setRange(-10, 100)
        widget.setSingleStep(0.5)

        widget.valueChanged.connect(self.value_changed)
        widget.sliderMoved.connect(self.slider_position)
        widget.sliderPressed.connect(self.slider_pressed)
        widget.sliderReleased.connect(self.slider_released)

        self.setCentralWidget(widget)
Exemplo n.º 17
0
class Demo(QWidget):
    def __init__(self):
        super(Demo, self).__init__()
        self.setWindowTitle('QDial')  # 1
        self.dial = QDial(self)
        self.dial.setFixedSize(100, 100)  # 2
        self.dial.setRange(0, 100)  # 3
        self.dial.setNotchesVisible(False)  # 4
        self.dial.valueChanged.connect(self.on_change_func)  # 5
        self.label = QLabel('0', self)
        self.label.setFont(QFont('Arial Black', 20))
        self.h_layout = QHBoxLayout()
        self.h_layout.addWidget(self.dial)
        self.h_layout.addWidget(self.label)
        self.setLayout(self.h_layout)

    def on_change_func(self):
        self.label.setText(str(self.dial.value()))
Exemplo n.º 18
0
class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.slider = QSlider(Qt.Horizontal, self)
        # QSlider 위젯을 하나 만들었습니다. Qt.Horizontal 또는
        # Qt.Vertical을 입력해줌으로써 수평 또는 수직 방향을 설정합니다.
        self.slider.move(30, 30)
        self.slider.setRange(0, 50)
        # setRange() 메서드로 값의 범위를 0에서 50까지로 설정합니다.
        # setSingleStep() 메서드는 조절 가능하는 최소 단위를 설정합니다
        self.slider.setSingleStep(2)

        self.dial = QDial(self)
        # QDial 위젯을 하나 만들었습니다.
        self.dial.move(30, 50)
        self.dial.setRange(0, 50)
        # 슬라이더와 마찬가지로 setRange() 메서드로 범위를 정해줍니다.

        btn = QPushButton('Default', self)
        btn.move(35, 160)

        self.slider.valueChanged.connect(self.dial.setValue)
        self.dial.valueChanged.connect(self.slider.setValue)
        # 슬라이더와 다이얼의 값이 변할 때 발생하는 시그널을 각각 다이얼과
        # 슬라이더의 값을 조절해주는 메서드 (setValue)에 서로 연결함으로써
        # 두 위젯의 값이 언제나 일치하도록 해줍니다.
        btn.clicked.connect(self.button_clicked)
        # 'Default' 푸시 버튼을 클릭하면 발생하는 시그널을 button_clicked 메서드에 연결합니다.

        self.setWindowTitle('QSlider and QDial')
        self.setGeometry(300, 300, 400, 200)
        self.show()

    def button_clicked(self):
        self.slider.setValue(0)
        self.dial.setValue(0)
Exemplo n.º 19
0
    def initUi(self):

        layout = QGridLayout()
        label = QLabel()

        spinbox = QSpinBox()
        spinbox.setRange(0, 100)
        spinbox.setSingleStep(5)

        dial = QDial()
        dial.setRange(0, 100)

        spinbox.valueChanged.connect(
            lambda: self.on_value_changed(spinbox, dial, label))

        dial.valueChanged.connect(
            lambda: self.on_value_changed(dial, spinbox, label))

        layout.addWidget(spinbox, 0, 0)
        layout.addWidget(dial, 0, 4)
        layout.addWidget(label, 1, 0)
        self.setLayout(layout)
Exemplo n.º 20
0
class 다이얼위젯(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.dial = QDial(self)
        self.dial.move(30, 20)

        self.dial2 = QDial(self)
        self.dial2.move(200, 20)
        self.dial2.setRange(0, 50)
        self.dial2.setNotchesVisible(True)

        self.label1 = QLabel('다이얼 1값', self)
        self.label1.move(40, 130)
        self.label2 = QLabel('다이얼 2값', self)
        self.label2.move(210, 130)

        btn = QPushButton('기본값으로 되돌리기', self)
        btn.move(150, 200)

        self.dial.valueChanged.connect(self.chageValue)
        self.dial2.valueChanged.connect(self.chageValue)

        btn.clicked.connect(self.btn_clicked)

        self.setGeometry(300, 300, 500, 400)
        self.setWindowTitle('QDial')
        self.show()

    def btn_clicked(self):
        self.dial.setValue(0)
        self.dial2.setValue(0)

    def chageValue(self):
        self.label1.setText(str(self.dial.value()))
        self.label2.setText(str(self.dial2.value()))
Exemplo n.º 21
0
class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'Ex5.8_QSlider_Qdial'
        self.posXY = (1200, 50)
        self.windowSize = (370, 250)
        self.initUI()

    def initUI(self):
        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.move(30, 30)
        self.slider.setRange(0, 50)
        self.slider.setSingleStep(2)

        self.dial = QDial(self)
        self.dial.move(30, 60)
        self.dial.setRange(0, 50)
        self.dial.setNotchesVisible(True)

        btn = QPushButton('RESET', self)
        btn.move(35, 190)

        self.slider.valueChanged.connect(self.dial.setValue)
        self.dial.valueChanged.connect(self.slider.setValue)
        btn.clicked.connect(self.button_clicked)

        self.show_basic()

    def button_clicked(self):
        self.slider.setValue(0)
        self.dial.setValue(0)


    def show_basic(self):
        self.setWindowTitle(self.title)
        self.setGeometry(*self.posXY, *self.windowSize)
        self.show()
Exemplo n.º 22
0
class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.slider = QSlider(
            Qt.Horizontal,
            self)  # 슬라이더 객체 생성(가로로 만들기), 수평으로 만들건지 수직으로 만들건지 내장 [상수]로 보내준다.
        # 상수는 대부분 Qt가 가지고 있기 때문에 값을 Qt에서 꺼내온다.(Qt.Horizontal / Qt.Vertical)
        self.slider.move(30, 30)  # 위치 설정
        self.slider.setRange(0, 50)  # 슬라이더의 min, max값 설정
        self.slider.setSingleStep(2)  # 한 번 이동시 이동할 틱 값 설정

        self.dial = QDial(self)  # 다이얼 객체 생성
        self.dial.move(30, 50)  # 다이얼 위치 설정
        self.dial.setRange(0, 50)  # 다이얼의 min, Max값 설정

        btn = QPushButton('Default', self)  # Default 라고 쓰여진 버튼 생성
        btn.move(35, 160)  # 버튼 위치 선정

        #slider 따로 dial 따로 하면 아래 3줄은 필요 없음
        self.slider.valueChanged.connect(
            self.dial.setValue)  # 슬라이더의 값에 변화가 일어나면 그 값을 dial.setValue로 보낸다.
        self.dial.valueChanged.connect(
            self.slider.setValue)  # 다이얼의 값이 변했을 때 그 값을 slider.setValue로 보낸다.
        btn.clicked.connect(
            self.button_clicked
        )  # 버튼이 클릭되었을 때 그 값을 button_clicked로 보내준다.(사용자가 만드는 함수)

        self.setWindowTitle('QSlider and QDial')
        self.setGeometry(300, 300, 400, 200)
        self.show()

    def button_clicked(self):
        self.slider.setValue(0)  # 슬라이더의 값을 0으로 설정
        self.dial.setValue(0)  # 다이얼의 값을 0으로 설정
Exemplo n.º 23
0
class Temperature_Page(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.NowTemperature = QLCDNumber(self)
        self.WantTemperature = QLCDNumber(self)
        self.SettingDial = QDial(self)
        self.lbNow = QLabel("현재 온도", self)
        self.lbWant = QLabel("희망 온도", self)
        self.NowFont = self.lbNow.font()
        self.NowFont.setPointSize(40)
        self.NowFont.setBold(True)

        self.lbNow.resize(300, 50)
        self.lbNow.move(50, 50)
        self.lbNow.setAlignment(Qt.AlignCenter)
        self.lbNow.setFont(self.NowFont)

        self.lbWant.resize(300, 50)
        self.lbWant.move(400, 50)
        self.lbWant.setAlignment(Qt.AlignCenter)
        self.lbWant.setFont(self.NowFont)

        self.NowTemperature.resize(300, 100)
        self.NowTemperature.move(50, 130)

        self.WantTemperature.resize(300, 100)
        self.WantTemperature.move(400, 130)

        self.SettingDial.resize(190, 190)
        self.SettingDial.setRange(-20, 20)
        self.SettingDial.setNotchesVisible(True)
        self.SettingDial.move(460, 250)
        self.NowTemperature.display(sensorValue)

        self.SettingDial.valueChanged.connect(self.WantTemperature.display)
Exemplo n.º 24
0
import sys

from PyQt5.QtWidgets import QApplication, QDial


def printValue(value):
    print(value, dial.value())

app = QApplication(sys.argv)

dial = QDial()

#dial.setMinimum(-15)
#dial.setMaximum(15)

dial.setRange(-15, 15)

dial.setNotchesVisible(True)

dial.setValue(5)   # Initial value

dial.valueChanged.connect(printValue)

dial.show()

# The mainloop of the application. The event handling starts from this point.
# The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead.
exit_code = app.exec_()

# The sys.exit() method ensures a clean exit.
# The environment will be informed, how the application ended.
Exemplo n.º 25
0
class QDialSlider(QWidget, QObject):
    '''New signals should only be defined in sub-classes of QObject. They must be part of the class definition and
    cannot be dynamically added as class attributes after the class has been defined.'''
    trigger = pyqtSignal()

    def __init__(self, name, maxV, bipolar=True, parent=None):
        super(QDialSlider, self).__init__(parent)
        self.overflow = False
        self.value = 0.0
        if (maxV > 10):
            self.slider_multi = 10
        else:
            self.slider_multi = 100
        # Object
        self.edit = QDoubleSpinBox()
        self.dial = QDial()
        self.slider = QSlider(Qt.Horizontal)
        self.scale = QScale(maxV, bipolar)
        self.layout = self.CreateGroup(name)
        self.timer = QtCore.QTimer()

        # Property
        self.dial.setRange(-10, 10)
        self.slider.setTickInterval(100)
        self.edit.setSingleStep(0.01)
        self.edit.setDecimals(2)
        if bipolar:
            self.edit.setRange(-maxV, maxV)
            self.slider.setRange(int(-maxV * self.slider_multi),
                                 int(maxV * self.slider_multi))
        else:
            self.edit.setRange(0, maxV)
            self.slider.setRange(0, int(maxV * self.slider_multi))

        # Event
        self.slider.valueChanged.connect(self.SliderChange)
        self.edit.valueChanged.connect(self.EditChange)
        self.dial.sliderPressed.connect(self.DialPress)
        self.dial.sliderReleased.connect(self.DialRelease)
        self.timer.timeout.connect(self.onTimer)

    def setValue(self, dvalue):
        self.value = dvalue

    def setOverflow(self):
        self.overflow = True

    #layout and style
    def CreateGroup(self, name):
        self.edit.setFixedSize(98, 32)
        self.dial.setFixedSize(80, 80)
        #self.slider.setTickInterval(10)
        self.slider.setFocusPolicy(Qt.StrongFocus)
        self.slider.setTickPosition(QSlider.TicksBothSides)

        self.edit.setAlignment(Qt.AlignRight)
        self.edit.setFont(QFont("Arial", 16))
        self.edit.setStyleSheet("color: rgb(36,36,36);")

        #layout
        hbox1 = QHBoxLayout()
        hbox1.addWidget(self.dial)
        hbox1.addWidget(self.edit, Qt.AlignCenter)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox1)
        vbox.addWidget(self.scale)
        vbox.addWidget(self.slider)

        groupBox = QGroupBox(name)
        groupBox.setLayout(vbox)
        return groupBox

    @pyqtSlot()
    def SliderChange(self):
        if (self.slider.hasFocus()):
            val = self.slider.value()
            self.edit.setValue(val / self.slider_multi)
            #print('SliderChange'+str(val/self.slider_multi))

    @pyqtSlot()
    def EditChange(self):
        val = self.edit.value()
        self.slider.setValue(int(val * self.slider_multi))
        if (self.overflow):
            self.overflow = False
        else:
            self.trigger.emit()
        #print('EditChange'+str(val))

    @pyqtSlot()
    def DialPress(self):
        self.timer.start(100)
        #print('DialPress')

    @pyqtSlot()
    def DialRelease(self):
        self.timer.stop()
        self.dial.setValue(0)
        #print('DialRelease')

    def onTimer(self):
        delta = self.dial.value()
        sign = lambda x: math.copysign(1, x)
        delta = sign(delta) * int((10**(abs(delta) / 4)) - 0.5) / 100
        self.edit.setValue(self.edit.value() + delta)
Exemplo n.º 26
0
class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        btn1 = QPushButton('&Button1', self)
        btn1.setCheckable(True)
        btn1.toggle()

        btn2 = QPushButton(self)
        btn2.setText('Button&2')

        btn3 = QPushButton('Button3', self)
        btn3.setEnabled(False)

        #label
        label = QLabel('나는 라벨', self)
        label.setAlignment(Qt.AlignCenter)
        font = label.font()
        font.setPointSize(10)
        font.setFamily('Times New Roman')
        font.setBold(True)
        label.setFont(font)

        #QCheckBox
        cb = QCheckBox('Show title', self)
        cb.move(20, 20)
        cb.toggle()
        #cb.stateChanged.connect(self.changeTitle)
        #여기선 제목을 바꿀 수 없는듯

        rbtn1 = QRadioButton('동구란 버튼', self)
        rbtn1.setChecked(True)
        rbtn2 = QRadioButton(self)
        rbtn2.setText('도옹구란 버튼')

        #ComboBox 생성
        #self.lbl = QLabel('Option1', self)
        cob = QComboBox(self)
        cob.addItem('Option1')
        cob.addItem('Option2')
        cob.addItem('Option3')
        cob.addItem('Option4')
        #cob.activated[str].connect(self.onActivated)

        #LineEdit 생성
        qle = QLineEdit(self)
        #qle.textChanged[str].connect(self.onChanged)

        #ProgressBar 진행상황 막대기
        self.pbar = QProgressBar(self)
        #self.pbar.setGeometry(30, 40, 200, 25)

        self.btnS = QPushButton('Start', self)
        self.btnS.clicked.connect(self.doAction)

        self.timer = QBasicTimer()
        self.step = 0

        #QSlider, QDial
        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.setRange(0, 50)
        self.slider.setSingleStep(2)
        self.dial = QDial(self)
        self.dial.setRange(0, 50)
        self.slider.valueChanged.connect(self.dial.setValue)
        self.dial.valueChanged.connect(self.slider.setValue)

        pixmap = QPixmap('Hanabi.PNG')

        lbl_img = QLabel()
        lbl_img.setPixmap(pixmap)
        lbl_size = QLabel('Width: ' + str(pixmap.width()) + ', Height: ' +
                          str(pixmap.height()))
        lbl_size.setAlignment(Qt.AlignCenter)

        self.lbl1 = QLabel('QSpinBox')
        self.spinbox = QSpinBox()
        self.spinbox.setMinimum(-10)
        self.spinbox.setMaximum(30)
        self.spinbox.setSingleStep(2)
        self.lbl2 = QLabel('0')

        self.spinbox.valueChanged.connect(self.value_changed)

        #doubleSpinBox
        self.lbl3 = QLabel('QDoubleSpinBox')
        self.dspinbox = QDoubleSpinBox()
        self.dspinbox.setRange(0, 100)
        self.dspinbox.setSingleStep(0.5)
        self.dspinbox.setPrefix('$ ')
        self.dspinbox.setDecimals(1)
        self.lbl4 = QLabel('$ 0.0')

        self.dspinbox.valueChanged.connect(self.value_changed)

        layout1 = QHBoxLayout()
        layout2 = QHBoxLayout()
        layout3 = QHBoxLayout()
        layout4 = QHBoxLayout()
        layout5 = QHBoxLayout()

        vlayout = QVBoxLayout()
        vlayout2 = QVBoxLayout()

        layout1.addWidget(btn1)
        layout1.addWidget(btn2)
        layout1.addWidget(cob)

        layout2.addWidget(label)
        layout2.addWidget(cb)
        layout2.addWidget(rbtn1)
        layout2.addWidget(rbtn2)

        layout3.addWidget(btn3)
        layout3.addWidget(qle)

        layout4.addWidget(self.slider)
        layout4.addWidget(self.dial)

        vlayout2.addWidget(self.lbl1)
        vlayout2.addWidget(self.spinbox)
        vlayout2.addWidget(self.lbl2)
        vlayout2.addWidget(self.lbl3)
        vlayout2.addWidget(self.dspinbox)
        vlayout2.addWidget(self.lbl4)

        layout5.addWidget(lbl_img)
        layout5.addLayout(vlayout2)

        vlayout.addLayout(layout1)
        vlayout.addLayout(layout3)
        vlayout.addLayout(layout2)
        vlayout.addWidget(self.pbar)
        vlayout.addWidget(self.btnS)
        vlayout.addLayout(layout4)
        vlayout.addLayout(layout5)
        self.setLayout(vlayout)

    def value_changed(self):
        self.lbl2.setText(str(self.spinbox.value()))

    def onActivated(self, text):
        self.lbl.setText(text)
        self.lbl.adjustSize()

    def onChanged(self, text):
        self.lbl.setText(text)
        self.lbl.adjustSize()

    def timerEvent(self, e):
        if self.step >= 100:
            self.timer.stop()
            self.btnS.setText('Finished')
            return

        self.step = self.step + 1
        self.pbar.setValue(self.step)

    def doAction(self):
        if self.timer.isActive():
            self.timer.stop()
            self.btnS.setText('Start')
        else:
            self.timer.start(100, self)
            self.btnS.setText('Stop')
Exemplo n.º 27
0
class MainWindow(QMainWindow):

    """Voice Changer main window."""

    def __init__(self, parent=None):
        super(MainWindow, self).__init__()
        self.statusBar().showMessage("Move Dial to Deform Microphone Voice !.")
        self.setWindowTitle(__doc__)
        self.setMinimumSize(240, 240)
        self.setMaximumSize(480, 480)
        self.resize(self.minimumSize())
        self.setWindowIcon(QIcon.fromTheme("audio-input-microphone"))
        self.tray = QSystemTrayIcon(self)
        self.center()
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        self.menuBar().addMenu("&File").addAction("Quit", lambda: exit())
        self.menuBar().addMenu("Sound").addAction(
            "STOP !", lambda: call('killall rec', shell=True))
        windowMenu = self.menuBar().addMenu("&Window")
        windowMenu.addAction("Hide", lambda: self.hide())
        windowMenu.addAction("Minimize", lambda: self.showMinimized())
        windowMenu.addAction("Maximize", lambda: self.showMaximized())
        windowMenu.addAction("Restore", lambda: self.showNormal())
        windowMenu.addAction("FullScreen", lambda: self.showFullScreen())
        windowMenu.addAction("Center", lambda: self.center())
        windowMenu.addAction("Top-Left", lambda: self.move(0, 0))
        windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position())
        # widgets
        group0 = QGroupBox("Voice Deformation")
        self.setCentralWidget(group0)
        self.process = QProcess(self)
        self.process.error.connect(
            lambda: self.statusBar().showMessage("Info: Process Killed", 5000))
        self.control = QDial()
        self.control.setRange(-10, 20)
        self.control.setSingleStep(5)
        self.control.setValue(0)
        self.control.setCursor(QCursor(Qt.OpenHandCursor))
        self.control.sliderPressed.connect(
            lambda: self.control.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.control.sliderReleased.connect(
            lambda: self.control.setCursor(QCursor(Qt.OpenHandCursor)))
        self.control.valueChanged.connect(
            lambda: self.control.setToolTip(f"<b>{self.control.value()}"))
        self.control.valueChanged.connect(
            lambda: self.statusBar().showMessage(
                f"Voice deformation: {self.control.value()}", 5000))
        self.control.valueChanged.connect(self.run)
        self.control.valueChanged.connect(lambda: self.process.kill())
        # Graphic effect
        self.glow = QGraphicsDropShadowEffect(self)
        self.glow.setOffset(0)
        self.glow.setBlurRadius(99)
        self.glow.setColor(QColor(99, 255, 255))
        self.control.setGraphicsEffect(self.glow)
        self.glow.setEnabled(False)
        # Timer to start
        self.slider_timer = QTimer(self)
        self.slider_timer.setSingleShot(True)
        self.slider_timer.timeout.connect(self.on_slider_timer_timeout)
        # an icon and set focus
        QLabel(self.control).setPixmap(
            QIcon.fromTheme("audio-input-microphone").pixmap(32))
        self.control.setFocus()
        QVBoxLayout(group0).addWidget(self.control)
        self.menu = QMenu(__doc__)
        self.menu.addAction(__doc__).setDisabled(True)
        self.menu.setIcon(self.windowIcon())
        self.menu.addSeparator()
        self.menu.addAction(
            "Show / Hide",
            lambda: self.hide() if self.isVisible() else self.showNormal())
        self.menu.addAction("STOP !", lambda: call('killall rec', shell=True))
        self.menu.addSeparator()
        self.menu.addAction("Quit", lambda: exit())
        self.tray.setContextMenu(self.menu)
        self.make_trayicon()

    def run(self):
        """Run/Stop the QTimer."""
        if self.slider_timer.isActive():
            self.slider_timer.stop()
        self.glow.setEnabled(True)
        call('killall rec ; killall play', shell=True)
        self.slider_timer.start(3000)

    def on_slider_timer_timeout(self):
        """Run subprocess to deform voice."""
        self.glow.setEnabled(False)
        value = int(self.control.value()) * 100
        command = f'play -q -V0 "|rec -q -V0 -n -d -R riaa bend pitch {value} "'
        print(f"Voice Deformation Value: {value}")
        print(f"Voice Deformation Command: {command}")
        self.process.start(command)
        if self.isVisible():
            self.statusBar().showMessage("Minimizing to System TrayIcon", 3000)
            print("Minimizing Main Window to System TrayIcon now...")
            sleep(3)
            self.hide()

    def center(self):
        """Center Window on the Current Screen,with Multi-Monitor support."""
        window_geometry = self.frameGeometry()
        mousepointer_position = QApplication.desktop().cursor().pos()
        screen = QApplication.desktop().screenNumber(mousepointer_position)
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        window_geometry.moveCenter(centerPoint)
        self.move(window_geometry.topLeft())

    def move_to_mouse_position(self):
        """Center the Window on the Current Mouse position."""
        window_geometry = self.frameGeometry()
        window_geometry.moveCenter(QApplication.desktop().cursor().pos())
        self.move(window_geometry.topLeft())

    def make_trayicon(self):
        """Make a Tray Icon."""
        if self.windowIcon() and __doc__:
            self.tray.setIcon(self.windowIcon())
            self.tray.setToolTip(__doc__)
            self.tray.activated.connect(
                lambda: self.hide() if self.isVisible()
                else self.showNormal())
            return self.tray.show()
Exemplo n.º 28
0
class window(QtWidgets.QMainWindow):   
   def __init__(self):
      super(window,self).__init__()
      self.currentlocal=0
      self.data=None
      self.checker=0
      self.lastcolored=0
      self.photo = QLabel(self)
      self.port=0
      self.pixmap = QPixmap('photo.png')
      self.pixmap = self.pixmap.scaled(600, 300, QtCore.Qt.KeepAspectRatio)
      self.photo.setPixmap(self.pixmap)

      self.labelgif=QLabel(self)      
      self.labelgif.setStyleSheet("QLabel { background-color : white;}");
      self.labelgif.setGeometry(100,50,500,430)
      self.movie = QtGui.QMovie('data.gif', QtCore.QByteArray(),self.labelgif)
      self.movie.setSpeed(100)
      self.labelgif.setMovie(self.movie) 
      self.movie.start()
      self.labelgif.setVisible(False)

      self.labelyazi=QLabel(self)
      self.labelgif1=QLabel(self)      
      self.labelgif1.setStyleSheet("QLabel { background-color : white;}")
      self.labelyazi.setText('G'+"\u00F6"+"zl"+"\u0259"+"yin..")
      font1=QtGui.QFont('Times',17)
      self.labelyazi.setFont(font1)
      self.labelyazi.setVisible(False)
      self.labelyazi.setGeometry(350,150,150,60)
      self.labelgif1.setGeometry(150,100,489,289)
      self.movie1 = QtGui.QMovie('wait.gif', QtCore.QByteArray(),self.labelgif1)
      self.movie1.setSpeed(100)
      self.labelgif1.setMovie(self.movie1) 
      self.movie1.start()
      self.labelgif1.setVisible(False)

      
      self.setWindowTitle("Diplom i\u015Fi v1")      
      self.setWindowIcon(QtGui.QIcon('pyicon.png'))
      self.button = QPushButton('PyQt5 button', self)#button yaradildi
      self.listw=QListWidget(self)#listWidget yaradildi
      self.button1=QPushButton(self)
      self.buttonlocal=QPushButton(self)
      self.buttonlocal.setText('Qo\u015F')
      self.button1.setText("Temperaturu"+" " +"\u00F6"+"l"+"\u00E7")
      self.dial=QDial(self)
      self.lcd=QLCDNumber(self)
      self.label=QLabel(self)
      self.labelrefresh=QLabel(self)
      self.obj=[]
   
      
      self.listCOM=QListWidget(self)
      self.spin=QSpinBox(self)
      self.radiosan=QRadioButton(self)
      self.radiosan.setText("Saniy"+"\u0259")
      self.radiodeq=QRadioButton(self)
      self.radiodeq.setText("D"+"\u0259"+"qiq"+"\u0259")
      self.starting()
      self.initUI()

      
   def initUI(self):                  
        self.setFixedSize(700,500)
        self.dial.setNotchesVisible(True)
        self.labelrefresh.setText('Yenil\u0259m\u0259k \u00FC\u00E7\u00FCn F5 d\u00FCym\u0259sini s\u0131x\u0131n ')
        self.labelrefresh.setStyleSheet("QLabel{background-color: yellow; }")
        font=QtGui.QFont('Times',10,QtGui.QFont.Bold)
        self.labelrefresh.setFont(font)
        self.lcd.setVisible(False)
        self.photo.setVisible(False)
        self.photo.raise_()            
        self.labelgif.raise_()
        self.labelgif1.raise_()
        self.labelyazi.raise_()
        self.spin.setRange(1,60)
        self.dial.setRange(1,60)
        self.button.setText("\u015E"+"\u0259"+"b\u0259k\u0259ni yoxla")
        self.button1.setEnabled(False)
        self.button.setEnabled(False)
        self.spin.setEnabled(False)
        self.dial.setEnabled(False)
        self.radiosan.setEnabled(False)
        self.radiodeq.setEnabled(False)
        self.label.setText('Qo\u015Fulmu'+'\u015F cihaz yoxdur')
        self.label.setStyleSheet("QLabel { background-color : #e20000; color : black; }");
        newfont = QtGui.QFont('Times',11) 
        self.label.setFont(newfont)        
        

        
        #geometries
        self.setGeometry(40,50,700,500)
        self.button.setGeometry(20,40,120,50)
        self.listw.setGeometry(380,160,300,200)
        self.button1.setGeometry(575,40,120,50)
        self.dial.setGeometry(40,400,75,70)
        self.spin.setGeometry(150,425,50,25)
        self.radiosan.setGeometry(150,400,75,25)
        self.radiodeq.setGeometry(150,380,75,25)
        self.lcd.setGeometry(300,40,100,50)
        self.buttonlocal.setGeometry(150,40,125,50)
        self.label.setGeometry(520,440,155,30)
        self.listCOM.setGeometry(20,160,300,200)
        self.labelrefresh.setGeometry(20,100,220,30)
        self.photo.setGeometry(50,100,600,300)
        
    
        #events
        self.buttonlocal.clicked.connect(self.checklocal)
        self.button.clicked.connect(self.thread1)
        self.button.clicked.connect(self.threadnetwork)
        self.dial.valueChanged.connect(self.spin.setValue)
        self.spin.valueChanged.connect(self.dial.setValue)
        self.listCOM.doubleClicked.connect(self.showdialog)
        self.listw.doubleClicked.connect(self.showdialogremote)
        self.button1.clicked.connect(self.thread) # communication
        self.radiodeq.clicked.connect(self.spinvalue)
        self.radiosan.clicked.connect(self.dialvalue)
        self.button1.clicked.connect(self.threadback)


    
   def threadback(self):
      if  self.radiodeq.isChecked() or self.radiosan.isChecked():
         self.thread1=threading.Thread(target=self.send)
         self.thread1.start()
      else:
         pass
   def loading(self):
      m=loading()
      

      
   def send(self):
      try:    
         self.currentlocal.open()
         remotestr=self.listw.currentItem().text()
         li=remotestr.split("-")
         xbee_network=self.currentlocal.get_network()         
         remote=xbee_network.get_device_by_64(XBee64BitAddress.from_hex_string(li[0]))
         arr_64=self.currentlocal.get_64bit_addr()
         NEW_TIMEOUT_FOR_SYNC_OPERATIONS = 1
         self.currentlocal.set_sync_ops_timeout(NEW_TIMEOUT_FOR_SYNC_OPERATIONS)
         if self.radiosan.isChecked():
            self.currentlocal.send_data(remote,str(arr_64)+"-"+str(self.spin.value()))
         else:
            self.currentlocal.send_data(remote,str(arr_64)+"-"+str(self.spin.value()*60))
         self.labelgif1.setVisible(False)     
         
                   
         self.labelgif1.setVisible(True)
         self.labelyazi.setVisible(True)
         while(True):
            self.data=self.currentlocal.read_data()
            if(self.data!=None):
               self.data=self.data.data.decode()
               self.labelgif1.setVisible(False)
               self.labelyazi.setVisible(False)
               break 
             
         self.currentlocal.close()
         
         data_list=self.data.split(',')
         self.labelgif.setVisible(True)
         
         objects = []
         performance=[]
         for i in range(1,len(data_list)):
            objects.append(i)
         for i in range(len(data_list)-1):
            li=data_list[i]
            li=li.split('-')
            performance.append(li[1])
         
         y_pos = np.arange(len(objects))
         objects=tuple(objects)
         plt.figure("Qrafik")
         plt.xticks(y_pos, objects)
         plt.ylabel('Temperatur')
         plt.xlabel('Zaman')
         plt.plot(y_pos,performance)
         self.labelgif.setVisible(False)
         plt.show()
         self.data=None
         
      except:
         print('salam')
         self.currentlocal.close()
      
         

         
   def showdialog(self): 
      try:
         li=self.listCOM.currentItem().text().split('-')
         local=XBeeDevice(li[2],9600)
         local.open()
         arr_64=local.get_64bit_addr()
         arr_16=local.get_16bit_addr()
         arr_node=local.get_node_id()
         arr_pro=local.get_protocol()
         arr_hard=local.get_hardware_version()
         local.close()
         dlg=dialog(arr_64,arr_16,arr_node,arr_pro,arr_hard)
      except:
         pass    #exception

      
   def showdialogremote(self): 
      li=self.listw.currentItem().text().split('-')
      if self.checker !=0:
         self.lastcolored.setBackground(QtGui.QColor(255,255,255))
         
      self.lastcolored=self.listw.currentItem()
      self.listw.currentItem().setBackground(QtGui.QColor(239, 255, 25))
      try:
         self.currentlocal.open()
         
         xbee_network=self.currentlocal.get_network()
         
         remote=xbee_network.get_device_by_64(XBee64BitAddress.from_hex_string(li[0]))
         
         arr_64=remote.get_64bit_addr()
         
         arr_16=remote.get_16bit_addr()
         arr_node=remote.get_node_id()
         arr_pro=remote.get_protocol()
         arr_hard=remote.get_hardware_version()
         self.currentlocal.close()
         dlg=dialog(arr_64,arr_16,arr_node,arr_pro,arr_hard)
         self.checker=1
      except:
         pass # exception
      

   def spinvalue(self):
      self.dial.setRange(1,60)
      self.spin.setRange(1,60)
      self.dial.setValue(1)
   def dialvalue(self):
      self.dial.setRange(4,60)
      self.spin.setRange(4,60)
      self.dial.setValue(4)
      
        
   def keyPressEvent(self, event):
      key = event.key()
      if key == QtCore.Qt.Key_F5:
         self.threadrefresh()


      

   def checklocal(self):                                               
      try:         
         if (self.currentlocal !=0):
            for i in range(0,self.listCOM.count()):
                 self.listCOM.item(i).setBackground(QtGui.QColor(255, 255, 255))
         self.listCOM.currentItem().setBackground(QtGui.QColor(97, 255, 66))
         li=self.listCOM.currentItem().text().split('-')
         self.currentlocal = XBeeDevice(li[2], 9600)
         self.port=li[2]        
         self.currentCOM=self.listCOM.currentItem().text()
         self.currentlocal.open()
         self.currentlocal.close()
         self.listw.clear()
         self.button1.setEnabled(True)
         self.button.setEnabled(True)
         self.spin.setEnabled(True)
         self.dial.setEnabled(True)     
         self.radiosan.setEnabled(True)
         self.radiodeq.setEnabled(True)
         if platform.system()=='Linux':
            self.label.setGeometry(500,440,180,30)
         self.label.setText('Qo\u015Fulmu'+'\u015F port: '+str(li[2]))
         self.checker=0  
         self.label.setStyleSheet("QLabel { background-color : #22ce00; color : white; }")
         
         
         
         
      except:
         QMessageBox.about(self, 'Yanl\u0131\u015F', 'Lokal cihaz\u0131n portu do\u011Fru deyil')

   def refresh(self):                                                                  
      self.listCOM.clear()
      index=0
      if platform.system()=='Windows':
         for i in range(0,257):
               try:               
                  local_xbee = XBeeDevice('COM'+str(i), 9600)
                  local_xbee.open()
                  addr64=local_xbee.get_64bit_addr()
                  noid=local_xbee.get_node_id()
                  local_xbee.close()
                  self.listCOM.addItem(str(addr64)+"-"+str(noid)+"-"+'COM'+str(i))
                  if(self.port=='COM'+str(i)):               
                     self.listCOM.item(index).setBackground(QtGui.QColor(97, 255, 66))
                  index+=1
               except:
                  pass
      elif platform.system()=='Linux':
         for i in range(257):
            try:               
               local_xbee = XBeeDevice('/dev/ttyUSB'+str(i), 9600)
               local_xbee.open()
               addr64=local_xbee.get_64bit_addr()
               noid=local_xbee.get_node_id()
               local_xbee.close()
               self.listCOM.addItem(str(addr64)+"-"+str(noid)+"-"+'/dev/ttyUSB'+str(i))
               if(self.port=='/dev/ttyUSB'+str(i)):               
                  self.listCOM.item(index).setBackground(QtGui.QColor(97, 255, 66))
               index+=1
            except:
               pass
      self.checker=0
         
      
      

         
        
   def thread(self):                                               
      if  self.radiodeq.isChecked() or self.radiosan.isChecked():
         self.thread=threading.Thread(target=self.timing)
         self.thread.start()
      else:
         QMessageBox.about(self, 'Yanl\u0131\u015F', 'Zaman vahidini se\u00E7in')

         
            
            
   def thread1(self):                                                          
      if  self.radiodeq.isChecked() or self.radiosan.isChecked():
         self.thread1=threading.Thread(target=self.scan)
         self.thread1.start()
      else:
         QMessageBox.about(self, 'Yanl\u0131\u015F', 'Zaman vahidini se\u00E7in')

   def threadnetwork(self):
      if  self.radiodeq.isChecked() or self.radiosan.isChecked():
         self.thread1=threading.Thread(target=self.network)
         self.thread1.start()
      else:
         pass


   def network(self):
      try:
         self.button1.setEnabled(False)
         self.buttonlocal.setEnabled(False)
         self.button.setEnabled(False)
         self.button1.setEnabled(False)
         self.spin.setEnabled(False)
         self.dial.setEnabled(False)    
         self.radiosan.setEnabled(False)
         self.radiodeq.setEnabled(False)
         self.listw.clear()
         self.currentlocal.open()
         xbee_network=self.currentlocal.get_network()
         xbee_network.clear()
         listdev=[]
         def callback_device_discovered(remote):
            listdev.append(str(remote))
         if self.radiosan.isChecked():
            if(self.spin.value()>25):
               defe=int((self.spin.value())/25)
               qaliqsan=(self.spin.value())%25
               for i in range(0,defe):
                  xbee_network.set_discovery_timeout(22)  
                  xbee_network.add_device_discovered_callback(callback_device_discovered)
                  xbee_network.start_discovery_process()
                  while xbee_network.is_discovery_running():
                     QtCore.QThread.msleep(100)
               if(qaliqsan<4):
                  add=q=4-qaliqsan
                  xbee_network.set_discovery_timeout(qaliqsan+add)  
                  xbee_network.add_device_discovered_callback(callback_device_discovered)
                  xbee_network.start_discovery_process()
                  while xbee_network.is_discovery_running():
                     QtCore.QThread.msleep(100)
               else:
                  xbee_network.set_discovery_timeout(qaliqsan) 
                  xbee_network.add_device_discovered_callback(callback_device_discovered)
                  xbee_network.start_discovery_process()
                  while xbee_network.is_discovery_running():
                     QtCore.QThread.msleep(100)
                     
               
               self.currentlocal.close()
            else:
               
               xbee_network.set_discovery_timeout(self.spin.value())   
               xbee_network.add_device_discovered_callback(callback_device_discovered)
               xbee_network.start_discovery_process()
               while xbee_network.is_discovery_running():
                  QtCore.QThread.msleep(100)
               self.currentlocal.close()
               
           
            self.photo.setVisible(True)
            listdev=list(set(listdev))
            for i in range(0,len(listdev)):
               self.listw.addItem(listdev[i])
            QtCore.QThread.msleep(1000)
            self.photo.setEnabled(True)
            self.buttonlocal.setEnabled(True)
            self.button1.setEnabled(True)
            self.button.setEnabled(True)
            self.spin.setEnabled(True)
            self.dial.setEnabled(True)     
            self.radiosan.setEnabled(True)
            self.radiodeq.setEnabled(True)
            self.photo.setVisible(False)
            
            

         if self.radiodeq.isChecked():
         
            defe=int((self.spin.value()*60)/25)
            qaliqsan=(self.spin.value()*60)%25
            for i in range(0,defe):
               xbee_network.set_discovery_timeout(22)  # 24 seconds + saniye elave.
               xbee_network.add_device_discovered_callback(callback_device_discovered)
               xbee_network.start_discovery_process()
               while xbee_network.is_discovery_running():
                  QtCore.QThread.msleep(100)
            xbee_network.set_discovery_timeout(qaliqsan)  # qaliq saniye.
            xbee_network.add_device_discovered_callback(callback_device_discovered)
            xbee_network.start_discovery_process()
            while xbee_network.is_discovery_running():
               QtCore.QThread.msleep(100)
            self.currentlocal.close()
         else:
            xbee_network.set_discovery_timeout(self.spin.value())  # qaliq saniye 
            xbee_network.add_device_discovered_callback(callback_device_discovered)
            xbee_network.start_discovery_process()
            while xbee_network.is_discovery_running():
               QtCore.QThread.msleep(100)
            self.currentlocal.close()
            
         self.photo.setVisible(True)  
         listdev=list(set(listdev))
         for i in range(0,len(listdev)):
            self.listw.addItem(listdev[i])
         QtCore.QThread.msleep(2000)
         self.buttonlocal.setEnabled(True)
         self.button1.setEnabled(True)
         self.button.setEnabled(True)
         self.spin.setEnabled(True)
         self.dial.setEnabled(True)
         self.radiosan.setEnabled(True)
         self.radiodeq.setEnabled(True)
         self.photo.setVisible(False)
         
      except:
         self.currentlocal.close()





   def threadrefresh(self):
      t=threading.Thread(target=self.refresh)
      t.start()
      


   #UI has been finished
      
   def timing(self):
      QtCore.QThread.msleep(1000)
      self.button1.setEnabled(False)
      if(self.radiodeq.isChecked()):
         self.lcd.setVisible(True)
         j=self.spin.value()*60
         k=self.spin.value()
         if(k<10):
            self.lcd.display("0{}:00".format(k))
            QtCore.QThread.msleep(1000)
         else:
            self.lcd.display("{}:00".format(k))
            QtCore.QThread.msleep(1000)
            
         j-=1
         k-=1
         while(j>-1):
            if(k<10):
               if(j%60<10):
                  if(j%60 is 0):                     
                     self.lcd.display("0{}:0{}".format(k,j%60))
                     k-=1
                     j-=1
                     QtCore.QThread.msleep(1000)
                     continue
                  self.lcd.display("0{}:0{}".format(k,j%60))
                  app.processEvents()
                  QtCore.QThread.msleep(1000)                     
                  j-=1
               else:
                  self.lcd.display("0{}:{}".format(k,j%60))
                  QtCore.QThread.msleep(1000)                     
                  j-=1
            else:
               if(j%60 is 0):
                  self.lcd.display("0{}:0{}".format(k,j%60))
                  k-=1
                  j-=1
                  QtCore.QThread.msleep(1000)
                  continue
               if(j%60<10):
                  self.lcd.display("{}:0{}".format(k,j%60))
                  QtCore.QThread.msleep(1000)
                  j-=1
               else:
                  self.lcd.display("{}:{}".format(k,j%60))
                  QtCore.QThread.msleep(1000)                     
                  j-=1
         self.lcd.setVisible(False)
         self.button1.setEnabled(True)

      elif (self.radiosan.isChecked()):
         self.lcd.setVisible(True)
         timing=self.spin.value()
         for i in range(timing,-1,-1):                     
            if(i<10):
               self.lcd.display("00:0{}".format(i))
               QtCore.QThread.msleep(1000)
               
            else:
               self.lcd.display("00:{}".format(i))
               QtCore.QThread.msleep(1000)
         self.lcd.setVisible(False)
         self.button1.setEnabled(True)

   def starting(self):
      splash=QtWidgets.QSplashScreen(QtGui.QPixmap('splash.jpg'),QtCore.Qt.WindowStaysOnTopHint)
      splash.show()
      for i in range(0,257):
         app.processEvents()
         if (i is 50):
               splash.showMessage("<h1><font color=#608fdb>Proqram başladılır!</font></h1>", QtCore.Qt.AlignTop)
               QtCore.QThread.msleep(1000)
         try:
            if (platform.system() == 'Windows'):
               local_xbee = XBeeDevice('COM'+str(i), 9600)
               local_xbee.open()
               addr64=local_xbee.get_64bit_addr()
               noid=local_xbee.get_node_id()
               local_xbee.close()
               self.listCOM.addItem(str(addr64)+"-"+str(noid)+"-"+'COM'+str(i))
            elif (platform.system() == 'Linux'):
               local_xbee = XBeeDevice('/dev/ttyUSB'+str(i), 9600)
               local_xbee.open()
               addr64=local_xbee.get_64bit_addr()
               noid=local_xbee.get_node_id()
               local_xbee.close()
               self.listCOM.addItem(str(addr64)+"-"+str(noid)+"-"+'/dev/ttyUSB'+str(i))         
         except:
            pass
      splash.close()

         
         
         



   def createlistw(self):
       self.listw.clear()
       for i in range(0,9):
          self.obj.append(i)
          self.obj[i]=elements()
          self.obj[i].t=[10,20,30,40,2,3,4,5,6]
          self.obj[i].s=[5,6,7,8,9,1,2,3,4,5,88]
          self.listw.addItem(str(self.obj[i].t[i]))

            
           

   def scan(self):
      self.button.setEnabled(False)

      if(self.radiodeq.isChecked()):
         self.lcd.setVisible(True)
         j=self.spin.value()*60
         k=self.spin.value()
         if(k<10):
            self.lcd.display("0{}:00".format(k))
            QtCore.QThread.msleep(1000)
         else:
            self.lcd.display("{}:00".format(k))
            QtCore.QThread.msleep(1000)
            
         j-=1
         k-=1
         while(j>-1):
            if(k<10):
               if(j%60<10):
                  if(j%60 is 0):
                     self.lcd.display("0{}:0{}".format(k,j%60))
                     k-=1
                     j-=1
                     QtCore.QThread.msleep(1000)
                     continue
                  self.lcd.display("0{}:0{}".format(k,j%60))
                  app.processEvents()
                  QtCore.QThread.msleep(1000)                     
                  j-=1
               else:
                  self.lcd.display("0{}:{}".format(k,j%60))
                  QtCore.QThread.msleep(1000)                     
                  j-=1
            else:
               if(j%60 is 0):
                  self.lcd.display("0{}:0{}".format(k,j%60))
                  k-=1
                  j-=1
                  QtCore.QThread.msleep(1000)
                  continue
               if(j%60<10):
                  self.lcd.display("{}:0{}".format(k,j%60))
                  QtCore.QThread.msleep(1000)
                  j-=1
               else:
                  self.lcd.display("{}:{}".format(k,j%60))
                  QtCore.QThread.msleep(1000)                     
                  j-=1
         self.lcd.setVisible(False)
         self.button.setEnabled(True)
      elif (self.radiosan.isChecked()):
         self.lcd.setVisible(True)
         timing=self.spin.value()
         for i in range(timing,-1,-1):
            if(i<10):
               self.lcd.display("00:0{}".format(i))
               QtCore.QThread.msleep(1000)                     
            else:
               self.lcd.display("00:{}".format(i))
               QtCore.QThread.msleep(1000)
         self.lcd.setVisible(False)
         self.button.setEnabled(True)
class ControlWidget(QDialog):
    def __init__(self, control_board, parent=None):
        super(ControlWidget, self).__init__(parent)
        self.control_board = control_board
        self.originalPalette = QApplication.palette()

        styleComboBox = QComboBox()
        styleComboBox.addItems(QStyleFactory.keys())

        styleLabel = QLabel("&Style:")
        styleLabel.setBuddy(styleComboBox)

        self.useStylePaletteCheckBox = QCheckBox("&Use style's standard palette")
        self.useStylePaletteCheckBox.setChecked(True)

        self.createCarCmdWidget()

        mainLayout = QGridLayout()
        mainLayout.addWidget(self.cmdGroupBox, 0, 0)
        self.setLayout(mainLayout)

        self.setWindowTitle("Styles")
        self.changeStyle('Windows')

    def changeStyle(self, styleName):
        QApplication.setStyle(QStyleFactory.create(styleName))
        self.changePalette()

    def changePalette(self):
        if (self.useStylePaletteCheckBox.isChecked()):
            QApplication.setPalette(QApplication.style().standardPalette())
        else:
            QApplication.setPalette(self.originalPalette)


    def createControlWidget(self):
        control_group_box = QGroupBox("Speed")

        self.speed_dial = QDial(self.cmdGroupBox)
        self.speed_dial.setRange(-100, 100)
        self.speed_dial.setValue(0)
        self.speed_dial.setNotchesVisible(True)
        self.speed_dial.setTracking(False)
        self.speed_dial.valueChanged.connect(self.speed_changed)

        self.speed_stop_button = QPushButton("Stop")
        self.speed_stop_button.released.connect(self.speed_stop)

        layout = QGridLayout()
        layout.addWidget(self.speed_dial, 1, 1)
        layout.addWidget(self.speed_stop_button, 3, 1)

        control_group_box.setLayout(layout)

        self.cmd_layout.addWidget(control_group_box, 1, 1)

        control_group_box = QGroupBox("Steering")

        self.steering_dial = QDial(self.cmdGroupBox)
        self.steering_dial.setRange(-100, 100)
        self.steering_dial.setValue(0)
        self.steering_dial.setNotchesVisible(True)
        self.steering_dial.setTracking(False)
        self.steering_dial.valueChanged.connect(self.steering_changed)

        self.steering_stop_button = QPushButton("Stop")
        self.steering_stop_button.released.connect(self.steering_stop)

        layout = QGridLayout()
        layout.addWidget(self.steering_dial, 1, 1)
        layout.addWidget(self.steering_stop_button, 3, 1)

        control_group_box.setLayout(layout)

        self.cmd_layout.addWidget(control_group_box, 1, 2)

        self.arm_button = QPushButton("Arm")
        self.arm_button.released.connect(self.set_arm_mode)

        self.manual_button = QPushButton("Manual")
        self.manual_button.released.connect(self.set_manual_mode)

        self.cmd_layout.addWidget(self.arm_button, 1, 3)
        self.cmd_layout.addWidget(self.manual_button, 2, 3)




    def steering_changed(self):
        control_board.set_steering(self.steering_dial.value())

    def steering_stop(self):
        control_board.set_steering(0)

    def speed_changed(self):
        control_board.set_speed(self.speed_dial.value())

    def speed_stop(self):
        control_board.set_speed(0)

    def set_arm_mode(self):
        control_board.set_mode(car_state.ARM)

    def set_manual_mode(self):
        control_board.set_mode(car_state.MANUAL)

    def createCarCmdWidget(self):
        self.cmdGroupBox = QGroupBox("Cmd group")
        self.cmd_layout = QGridLayout()

        self.createControlWidget()

        self.cmdGroupBox.setLayout(self.cmd_layout)
Exemplo n.º 30
0
class MyApp(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        # QLabel
        label1 = QLabel('Label1', self)
        label1.setAlignment(Qt.AlignCenter)
        font1 = label1.font()
        font1.setPointSize(15)
        label1.setFont(font1)

        label2 = QLabel('Label2', self)
        label2.setAlignment(Qt.AlignVCenter)
        font2 = label2.font()
        font2.setFamily('Consolas')
        font2.setBold(True)
        label2.setFont(font2)

        label3 = QLabel('Label3', self)
        label3.setAlignment(Qt.AlignHCenter)
        font3 = label3.font()
        font3.setPointSize(8)
        label3.setFont(font3)

        # QCheckBox
        checkbox1 = QCheckBox('CheckBox1', self)
        checkbox1.toggle()
        checkbox1.stateChanged.connect(self.changeTitle)

        checkbox2 = QCheckBox('CheckBox2', self)
        checkbox2.setTristate()

        checkbox3 = QCheckBox(self)
        checkbox3.setText('CheckBox3')

        # QPushButton
        btn1 = QPushButton('&Button1', self)
        btn1.setCheckable(True)
        btn1.toggle()

        btn2 = QPushButton(self)
        btn2.setText('&Button2')

        btn3 = QPushButton('&Button3', self)
        btn3.setEnabled(False)

        # QRadioButton
        rbtn1 = QRadioButton('RadioButton1', self)
        rbtn1.setChecked(True)

        rbtn2 = QRadioButton(self)
        rbtn2.setText('RadioButton2')

        # QComboBox
        cb = QComboBox(self)
        cb.addItem('Combo1')
        cb.addItem('Combo2')
        cb.addItem('Combo3')
        cb.addItem('Combo4')
        cb.activated[str].connect(self.onActivated)

        self.label4 = QLabel('Label4', self)

        # QLineEdit
        le = QLineEdit(self)
        le.textChanged[str].connect(self.onChanged)

        self.label5 = QLabel('Label5', self)

        # QProgressBar
        self.pbar1 = QProgressBar(self)

        pbar2 = QProgressBar(self)
        pbar2.setMaximum(0)
        pbar2.setMinimum(0)

        self.btn4 = QPushButton('Start', self)
        self.btn4.clicked.connect(self.doAction)

        self.timer = QBasicTimer()
        self.step = 0

        # QSlider & QDial
        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.setRange(0, 50)
        self.slider.setSingleStep(2)

        self.dial = QDial(self)
        self.dial.setRange(0, 50)

        self.slider.valueChanged.connect(self.dial.setValue)
        self.dial.valueChanged.connect(self.slider.setValue)

        btn5 = QPushButton('Default', self)
        btn5.clicked.connect(self.button_clicked)

        # QSplitter (QFrame)
        top = QFrame()
        top.setFrameShape(QFrame.Box)

        midleft = QFrame()
        midleft.setFrameShape(QFrame.StyledPanel)

        midright = QFrame()
        midright.setFrameShape(QFrame.Panel)

        bottom = QFrame()
        bottom.setFrameShape(QFrame.WinPanel)
        bottom.setFrameShadow(QFrame.Sunken)

        splitter1 = QSplitter(Qt.Horizontal)
        splitter1.addWidget(midleft)
        splitter1.addWidget(midright)

        splitter2 = QSplitter(Qt.Vertical)
        splitter2.addWidget(top)
        splitter2.addWidget(splitter1)
        splitter2.addWidget(bottom)

        # Layout
        grid = QGridLayout()
        self.setLayout(grid)

        grid.addWidget(label1, 0, 0)
        grid.addWidget(label2, 1, 0)
        grid.addWidget(label3, 2, 0)

        grid.addWidget(checkbox1, 0, 1)
        grid.addWidget(checkbox2, 1, 1)
        grid.addWidget(checkbox3, 2, 1)

        grid.addWidget(btn1, 0, 2)
        grid.addWidget(btn2, 1, 2)
        grid.addWidget(btn3, 2, 2)

        grid.addWidget(rbtn1, 3, 0)
        grid.addWidget(rbtn2, 3, 1)

        grid.addWidget(cb, 4, 0)
        grid.addWidget(self.label4, 4, 1)

        grid.addWidget(le, 5, 0)
        grid.addWidget(self.label5, 5, 1)

        grid.addWidget(self.btn4, 6, 0)
        grid.addWidget(self.pbar1, 6, 1)
        grid.addWidget(pbar2, 6, 2)

        grid.addWidget(btn5, 7, 0)
        grid.addWidget(self.slider, 7, 1)
        grid.addWidget(self.dial, 7, 2)

        grid.addWidget(splitter2, 8, 0)

        self.setWindowTitle('Widgets')
        self.setGeometry(300, 300, 300, 500)
        self.show()

    def changeTitle(self, state):
        if state == Qt.Checked:
            self.setWindowTitle('QCheckBox')
        else:
            self.setWindowTitle(' ')

    def onActivated(self, text):
        self.label4.setText(text)
        self.label4.adjustSize()

    def onChanged(self, text):
        self.label5.setText(text)
        self.label5.adjustSize()

    def doAction(self):
        if self.timer.isActive():
            self.timer.stop()
            self.btn4.setText('Start')
        else:
            self.timer.start(100, self)
            self.btn4.setText('Stop')

    def timerEvent(self, e):
        if self.step >= 100:
            self.timer.stop()
            self.btn4.setText('Finished')
            return
        self.step = self.step + 1
        self.pbar1.setValue(self.step)

    def button_clicked(self):
        self.slider.setValue(0)
        self.dial.setValue(0)
Exemplo n.º 31
0
class MainWindow(QMainWindow):
    """Voice Changer main window."""
    def __init__(self, parent=None):
        super(MainWindow, self).__init__()
        self.statusBar().showMessage("Move Dial to Deform Microphone Voice !.")
        self.setWindowTitle(__doc__)
        self.setMinimumSize(240, 240)
        self.setMaximumSize(480, 480)
        self.resize(self.minimumSize())
        self.setWindowIcon(QIcon.fromTheme("audio-input-microphone"))
        self.tray = QSystemTrayIcon(self)
        self.center()
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        self.menuBar().addMenu("&File").addAction("Quit", lambda: exit())
        self.menuBar().addMenu("Sound").addAction(
            "STOP !", lambda: call('killall rec', shell=True))
        windowMenu = self.menuBar().addMenu("&Window")
        windowMenu.addAction("Hide", lambda: self.hide())
        windowMenu.addAction("Minimize", lambda: self.showMinimized())
        windowMenu.addAction("Maximize", lambda: self.showMaximized())
        windowMenu.addAction("Restore", lambda: self.showNormal())
        windowMenu.addAction("FullScreen", lambda: self.showFullScreen())
        windowMenu.addAction("Center", lambda: self.center())
        windowMenu.addAction("Top-Left", lambda: self.move(0, 0))
        windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position())
        # widgets
        group0 = QGroupBox("Voice Deformation")
        self.setCentralWidget(group0)
        self.process = QProcess(self)
        self.process.error.connect(
            lambda: self.statusBar().showMessage("Info: Process Killed", 5000))
        self.control = QDial()
        self.control.setRange(-10, 20)
        self.control.setSingleStep(5)
        self.control.setValue(0)
        self.control.setCursor(QCursor(Qt.OpenHandCursor))
        self.control.sliderPressed.connect(
            lambda: self.control.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.control.sliderReleased.connect(
            lambda: self.control.setCursor(QCursor(Qt.OpenHandCursor)))
        self.control.valueChanged.connect(
            lambda: self.control.setToolTip("<b>" + str(self.control.value())))
        self.control.valueChanged.connect(lambda: self.statusBar().showMessage(
            "Voice deformation: " + str(self.control.value()), 5000))
        self.control.valueChanged.connect(self.run)
        self.control.valueChanged.connect(lambda: self.process.kill())
        # Graphic effect
        self.glow = QGraphicsDropShadowEffect(self)
        self.glow.setOffset(0)
        self.glow.setBlurRadius(99)
        self.glow.setColor(QColor(99, 255, 255))
        self.control.setGraphicsEffect(self.glow)
        self.glow.setEnabled(False)
        # Timer to start
        self.slider_timer = QTimer(self)
        self.slider_timer.setSingleShot(True)
        self.slider_timer.timeout.connect(self.on_slider_timer_timeout)
        # an icon and set focus
        QLabel(self.control).setPixmap(
            QIcon.fromTheme("audio-input-microphone").pixmap(32))
        self.control.setFocus()
        QVBoxLayout(group0).addWidget(self.control)
        self.menu = QMenu(__doc__)
        self.menu.addAction(__doc__).setDisabled(True)
        self.menu.setIcon(self.windowIcon())
        self.menu.addSeparator()
        self.menu.addAction(
            "Show / Hide", lambda: self.hide()
            if self.isVisible() else self.showNormal())
        self.menu.addAction("STOP !", lambda: call('killall rec', shell=True))
        self.menu.addSeparator()
        self.menu.addAction("Quit", lambda: exit())
        self.tray.setContextMenu(self.menu)
        self.make_trayicon()

    def run(self):
        """Run/Stop the QTimer."""
        if self.slider_timer.isActive():
            self.slider_timer.stop()
        self.glow.setEnabled(True)
        call('killall rec', shell=True)
        self.slider_timer.start(3000)

    def on_slider_timer_timeout(self):
        """Run subprocess to deform voice."""
        self.glow.setEnabled(False)
        value = int(self.control.value()) * 100
        cmd = 'play -q -V0 "|rec -q -V0 -n -d -R riaa bend pitch {0} "'
        command = cmd.format(int(value))
        log.debug("Voice Deformation Value: {0}".format(value))
        log.debug("Voice Deformation Command: {0}".format(command))
        self.process.start(command)
        if self.isVisible():
            self.statusBar().showMessage("Minimizing to System TrayIcon", 3000)
            log.debug("Minimizing Main Window to System TrayIcon now...")
            sleep(3)
            self.hide()

    def center(self):
        """Center Window on the Current Screen,with Multi-Monitor support."""
        window_geometry = self.frameGeometry()
        mousepointer_position = QApplication.desktop().cursor().pos()
        screen = QApplication.desktop().screenNumber(mousepointer_position)
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        window_geometry.moveCenter(centerPoint)
        self.move(window_geometry.topLeft())

    def move_to_mouse_position(self):
        """Center the Window on the Current Mouse position."""
        window_geometry = self.frameGeometry()
        window_geometry.moveCenter(QApplication.desktop().cursor().pos())
        self.move(window_geometry.topLeft())

    def make_trayicon(self):
        """Make a Tray Icon."""
        if self.windowIcon() and __doc__:
            self.tray.setIcon(self.windowIcon())
            self.tray.setToolTip(__doc__)
            self.tray.activated.connect(
                lambda: self.hide() if self.isVisible() else self.showNormal())
            return self.tray.show()
Exemplo n.º 32
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
                
        self.setWindowTitle("Homer")
        
        # Fuel rods
        self.fuel_rod_label = QLabel("Fuel Rod Position")
        self.fuel_rod_label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        
        self.fuel_rod_position_gauge = QDial()
        self.fuel_rod_position_gauge.setRange(0,100)
        self.fuel_rod_position_gauge.setSingleStep(1)
        self.fuel_rod_position_gauge.setNotchesVisible(True)
        
        self.fuel_rod_target_label = QLabel("Fuel Rod Position Target")
        self.fuel_rod_target_label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        
        self.fuel_rod_position = QSpinBox()
        self.fuel_rod_position.setMinimum(0)
        self.fuel_rod_position.setMaximum(100)
        self.fuel_rod_position.setSingleStep(1)
        self.fuel_rod_position.valueChanged.connect(self.fuel_rod_position_changed)
        
        fuel_rod_layout = QVBoxLayout()
        fuel_rod_layout.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
        fuel_rod_layout.addWidget(self.fuel_rod_label)
        fuel_rod_layout.addWidget(self.fuel_rod_position_gauge)
        fuel_rod_layout.addWidget(self.fuel_rod_target_label)
        fuel_rod_layout.addWidget(self.fuel_rod_position)
        
        fuel_rod_widget = QWidget()
        fuel_rod_widget.setLayout(fuel_rod_layout)
        
        # Primary loop controls
        self.primary_temp_label = QLabel("Primary Coolant Temp")
        self.primary_temp_label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        
        self.primary_temp_gauge = QDial()
        self.primary_temp_gauge.setRange(0,100)
        self.primary_temp_gauge.setSingleStep(1)
        self.primary_temp_gauge.setNotchesVisible(True)
        self.primary_temp_gauge.valueChanged.connect(self.primary_temp_value_changed)

        self.primary_pressure_label = QLabel("Primary Coolant Pressure")
        self.primary_pressure_label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        
        self.primary_pressure_gauge = QDial()
        self.primary_pressure_gauge.setRange(0,100)
        self.primary_pressure_gauge.setSingleStep(1)
        self.primary_pressure_gauge.setNotchesVisible(True)
        
        self.primary_pump_rpm_label = QLabel("Primary Pump RPM")
        self.primary_pump_rpm_label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        
        self.primary_pump_rpm = QSpinBox()
        self.primary_pump_rpm.setMinimum(0)
        self.primary_pump_rpm.setMaximum(100)
        self.primary_pump_rpm.setSingleStep(1)
        self.primary_pump_rpm.valueChanged.connect(self.primary_pump_rpm_changed)
        
        self.primary_relief_valve = QPushButton("vent primary")
        self.primary_relief_valve.setCheckable(True)
        self.primary_relief_valve.clicked.connect(self.primary_relief_valve_clicked)
        
        primary_loop_layout = QVBoxLayout()
        primary_loop_layout.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
        primary_loop_layout.addWidget(self.primary_temp_label)
        primary_loop_layout.addWidget(self.primary_temp_gauge)
        primary_loop_layout.addWidget(self.primary_pressure_label)
        primary_loop_layout.addWidget(self.primary_pressure_gauge)
        primary_loop_layout.addWidget(self.primary_pump_rpm_label)
        primary_loop_layout.addWidget(self.primary_pump_rpm)
        primary_loop_layout.addWidget(self.primary_relief_valve)
        
        primary_loop_widget = QWidget()
        primary_loop_widget.setLayout(primary_loop_layout)
        
        # Secondary loop controls
        self.secondary_temp_label = QLabel("Secondary Coolant Temp")
        self.secondary_temp_label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        
        self.secondary_temp_gauge = QDial()
        self.secondary_temp_gauge.setRange(0,100)
        self.secondary_temp_gauge.setSingleStep(1)
        self.secondary_temp_gauge.setNotchesVisible(True)
        self.secondary_temp_gauge.valueChanged.connect(self.secondary_temp_value_changed)
        
        self.secondary_pressure_label = QLabel("Secondary Coolant Pressure")
        self.secondary_pressure_label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        
        self.secondary_pressure_gauge = QDial()
        self.secondary_pressure_gauge.setRange(0,100)
        self.secondary_pressure_gauge.setSingleStep(1)
        self.secondary_pressure_gauge.setNotchesVisible(True)
        
        self.secondary_pump_rpm_label = QLabel("Secondary Pump RPM")
        self.secondary_pump_rpm_label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        
        self.secondary_pump_rpm = QSpinBox()
        self.secondary_pump_rpm.setMinimum(0)
        self.secondary_pump_rpm.setMaximum(100)
        self.secondary_pump_rpm.setSingleStep(1)
        self.secondary_pump_rpm.valueChanged.connect(self.secondary_pump_rpm_changed)
        
        self.secondary_relief_valve = QPushButton("vent secondary")
        self.secondary_relief_valve.setCheckable(True)
        self.secondary_relief_valve.clicked.connect(self.secondary_relief_valve_clicked)
        
        secondary_loop_layout = QVBoxLayout()
        secondary_loop_layout.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
        secondary_loop_layout.addWidget(self.secondary_temp_label)
        secondary_loop_layout.addWidget(self.secondary_temp_gauge)
        secondary_loop_layout.addWidget(self.secondary_pressure_label)
        secondary_loop_layout.addWidget(self.secondary_pressure_gauge)
        secondary_loop_layout.addWidget(self.secondary_pump_rpm_label)
        secondary_loop_layout.addWidget(self.secondary_pump_rpm)
        secondary_loop_layout.addWidget(self.secondary_relief_valve)
        
        secondary_loop_widget = QWidget()
        secondary_loop_widget.setLayout(secondary_loop_layout)
        
        # Turbine/generator
        self.turbine_rpm_label = QLabel("Turbine RPM")
        self.turbine_rpm_label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        
        self.turbine_rpm_gauge = QDial()
        self.turbine_rpm_gauge.setRange(0,100)
        self.turbine_rpm_gauge.setSingleStep(1)
        self.turbine_rpm_gauge.setNotchesVisible(True)
        
        self.generator_current_label = QLabel("Generator Current")
        self.generator_current_label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        
        self.generator_current_gauge = QDial()
        self.generator_current_gauge.setRange(0,100)
        self.generator_current_gauge.setSingleStep(1)
        self.generator_current_gauge.setNotchesVisible(True)
        
        turbine_layout = QVBoxLayout()
        turbine_layout.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
        turbine_layout.addWidget(self.turbine_rpm_label)
        turbine_layout.addWidget(self.turbine_rpm_gauge)
        turbine_layout.addWidget(self.generator_current_label)
        turbine_layout.addWidget(self.generator_current_gauge)
        
        turbine_layout_widget = QWidget()
        turbine_layout_widget.setLayout(turbine_layout)
        
        
        # Layout all the controls
        main_layout = QGridLayout()
        # Fuel rods
        main_layout.addWidget(fuel_rod_widget, 0,0)
        # Primary loop
        main_layout.addWidget(primary_loop_widget, 0, 1)
        # Secondary loop
        main_layout.addWidget(secondary_loop_widget,0,2)
        # TODO: Condenser
        # Turbine
        main_layout.addWidget(turbine_layout_widget,0,3)
        
        main_widget = QWidget()
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)
        
        # timer
        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.recurring_timer)
        self.timer.start()
        
    # Event handlers
    def recurring_timer(self):
        reactor.tick()
        self.fuel_rod_position_gauge.setValue(reactor.rod_position)
        self.primary_temp_gauge.setValue(reactor.primary_temp)
        self.primary_pressure_gauge.setValue(reactor.primary_pressure)
        self.secondary_temp_gauge.setValue(reactor.secondary_temp)
        self.secondary_pressure_gauge.setValue(reactor.secondary_pressure)
        self.turbine_rpm_gauge.setValue(reactor.turbine_rpm)
        self.generator_current_gauge.setValue(reactor.generator_current)
        
    def fuel_rod_position_changed(self, i):
        reactor.set_rod_position(i)
        
    def primary_temp_value_changed(self, i):
        print(i)
        
    def primary_relief_valve_clicked(self, checked):
        print(checked)
        if checked:
            reactor.open_primary_relief_valve()
        else:
            reactor.close_primary_relief_valve()
            
    def primary_pump_rpm_changed(self, i):
        reactor.set_primary_pump_rpm(i)
        
    def secondary_temp_value_changed(self, i):
        print(i)
        
    def secondary_relief_valve_clicked(self, checked):
        print(checked)
        if checked:
            reactor.open_secondary_relief_valve()
        else:
            reactor.close_secondary_relief_valve()
            
    def secondary_pump_rpm_changed(self, i):
        reactor.set_secondary_pump_rpm(i)
Exemplo n.º 33
0
class MyApp(QWidget):
    def __init__(self):
        super().__init__()

        self.m_response = ''
        self.m_response_complete = False
        self.s_response = ''
        self.s_reaponse_complete = False

        self.bilateral_start = False
        self.master_state = 0
        self.slave_state = 0

        self.m_theta = 0
        self.s_theta = 0

        self.command_to_master = []
        self.command_to_slave = []
        self.message_from_master = []
        self.message_from_slave = []
        self.listener_buffer = []
        self.m_header = False
        self.s_header = False

        self.listener_thread = threading.Thread(target=listener)
        self.speaker_thread = threading.Thread(target=speaker)

        self.initUI()

    def initUI(self):

        ############## Master param ###############
        groupbox_m = QGroupBox('Master param')

        master_serial_btn = QPushButton('Master_Serial', self)
        master_serial_btn.clicked.connect(self.master_serial)

        self.m_param_port = QLineEdit(self)
        hbox1 = QHBoxLayout()
        hbox1.addWidget(QLabel('Master_port', self))
        hbox1.addWidget(self.m_param_port)

        self.m_param_k = QLineEdit(self)
        hbox2 = QHBoxLayout()
        hbox2.addWidget(QLabel('Master_K', self))
        hbox2.addWidget(self.m_param_k)

        self.m_param_c = QLineEdit(self)
        hbox3 = QHBoxLayout()
        hbox3.addWidget(QLabel('Master_C', self))
        hbox3.addWidget(self.m_param_c)

        vbox_m = QVBoxLayout()
        vbox_m.addWidget(master_serial_btn)
        vbox_m.addLayout(hbox1)
        vbox_m.addLayout(hbox2)
        vbox_m.addLayout(hbox3)

        groupbox_m.setLayout(vbox_m)

        ################ Slave_param ###############
        groupbox_s = QGroupBox('Slave param')

        slave_serial_btn = QPushButton('Slave_Serial', self)
        slave_serial_btn.clicked.connect(self.slave_serial)

        self.s_param_port = QLineEdit(self)
        hbox4 = QHBoxLayout()
        hbox4.addWidget(QLabel('Slave_port', self))
        hbox4.addWidget(self.s_param_port)

        self.s_param_k = QLineEdit(self)
        hbox5 = QHBoxLayout()
        hbox5.addWidget(QLabel('Slave_K', self))
        hbox5.addWidget(self.s_param_k)

        self.s_param_c = QLineEdit(self)
        hbox6 = QHBoxLayout()
        hbox6.addWidget(QLabel('Slave_C', self))
        hbox6.addWidget(self.s_param_c)

        vbox_s = QVBoxLayout()
        vbox_s.addWidget(slave_serial_btn)
        vbox_s.addLayout(hbox4)
        vbox_s.addLayout(hbox5)
        vbox_s.addLayout(hbox6)

        groupbox_s.setLayout(vbox_s)

        ##############################################

        hbox7 = QHBoxLayout()
        hbox7.addWidget(groupbox_m)
        hbox7.addWidget(groupbox_s)

        Master_Bias = QPushButton('Master_Bias', self)
        Master_Bias.clicked.connect(self.master_bias)
        Slave_Bias = QPushButton('Slave_Bias', self)
        Slave_Bias.clicked.connect(self.slave_bias)
        hbox8 = QHBoxLayout()
        hbox8.addWidget(Master_Bias)
        hbox8.addWidget(Slave_Bias)

        Bilateral_Start = QPushButton('Bilateral_Start', self)
        Bilateral_Start.clicked.connect(self.bilateral_start_fn)
        Bilateral_Stop = QPushButton('Bilateral_Stop', self)
        Bilateral_Stop.clicked.connect(self.bilateral_stop_fn)
        hbox9 = QHBoxLayout()
        hbox9.addWidget(Bilateral_Start)
        hbox9.addWidget(Bilateral_Stop)

        Master_debug = QLabel('Master_debug', self)
        Slave_debug = QLabel('Slave_debug', self)
        hbox10 = QHBoxLayout()
        hbox10.addWidget(Master_debug)
        hbox10.addWidget(Slave_debug)

        self.dial = QDial(self)
        self.dial.setRange(-40, 40)
        self.dial.valueChanged.connect(self.dial_changed)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox7)
        vbox.addLayout(hbox8)
        vbox.addLayout(hbox9)
        vbox.addLayout(hbox10)
        vbox.addWidget(self.dial)

        self.setLayout(vbox)
        self.setWindowTitle('Bilateral Control (Team 2)')
        self.move(300, 300)
        self.resize(600, 800)
        self.show()

    def master_serial(self):
        print('master_serial')

        m_port = self.m_param_port.text()
        m_k = self.m_param_k.text()
        m_c = self.m_param_c.text()

        if len(m_port) == 0:
            print('you must input master port!!!!!!!!!!!!')
            sys.exit(app.exec_())

        self.m_port = serial.Serial(port='COM' + m_port, baudrate=115200)

        self.listener_thread.start()

        # wait for serial connection
        time.sleep(3)  # should be more than 2 sec

        # K command
        make_command('K', m_k, self.command_to_master)
        send(self.m_port, self.command_to_master)
        time.sleep(0.1)

        # C command
        make_command('C', m_c, self.command_to_master)
        send(self.m_port, self.command_to_master)
        time.sleep(0.1)

        #while self.m_response != 'Y' && self.master_state == 0:
        #    pass;
        #print("parameters is set.")
        #ex.m_response = ''

    def slave_serial(self):
        print('slave_serial')
        self.s_port = serial.Serial(port='COM3', baudrate=115200)
        #self.listener_thread.start()
        #self.speaker_thread.start()

    def master_bias(self):
        print('master_bias')
        send(self.m_port, 'B')

    def slave_bias(self):
        print('slave_bias')

    def bilateral_start_fn(self):
        print('bilateral_start')
        self.listener_thread.start()
        self.speaker_thread.start()
        send(self.m_port, 'S')
        self.bilateral_start = True

    def bilateral_stop_fn(self):
        print('bilateral_stop')
        send(self.m_port, 'P')
        self.bilateral_start = False

    def dial_changed(self, value):
        self.s_theta = value
        print('S : ' + str(self.s_theta))