Exemplo n.º 1
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)))
Exemplo n.º 2
0
class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.title = "PyQt5 Scroll Bar"
        self.top = 200
        self.left = 500
        self.width = 400
        self.height = 300

        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        vbox = QVBoxLayout()

        self.label = QLabel(self)
        self.label.setFont(QtGui.QFont("Sanserif", 15))

        self.dial = QDial()
        self.dial.setMaximum(0)
        self.dial.setMaximum(100)
        self.dial.setValue(30)
        self.label.setText("Dialer Value : " + str(self.dial.value()))
        self.dial.valueChanged.connect(self.dialer_changed)

        vbox.addWidget(self.dial)
        vbox.addWidget(self.label)
        self.setLayout(vbox)

        self.show()

    def dialer_changed(self):
        getValue = self.dial.value()
        self.label.setText(" Dialer Value : " + str(getValue))
Exemplo n.º 3
0
class TimerGB(QGroupBox):

    grab_timeout = pyqtSignal()
    gb_closed = pyqtSignal()

    def __init__(self, boxwidth, boxheight, parent=None):
        super(TimerGB, self).__init__(parent)
        QGroupBox("Set Interval")

        self.resize(boxwidth, boxheight)

        self.setWindowTitle("Timer")
        self.setFlat(True)

        self.timer_dial = QDial()
        self.timer_dial.setNotchesVisible(True)
        self.timer_dial.setMinimum(1)
        self.timer_dial.setMaximum(30)
        self.timer_dial.setValue(15)
        self.timer_dial.valueChanged.connect(self.on_dial_new_value)
        self.timer_dial.sliderReleased.connect(self.on_dial_released)

        self.value_display = QLabel()
        self.gbvlayout = QVBoxLayout()
        self.gbvlayout.addWidget(self.value_display)
        self.gbvlayout.addWidget(self.timer_dial)
        self.setLayout(self.gbvlayout)
        self.value_display.setText(str(self.timer_dial.value()) + " s")

        self.grab_timer = QTimer()

    def on_dial_new_value(self):
        self.value_display.setText(str(self.timer_dial.value()) + " s")

    def on_dial_released(self):
        self.timer_rate = self.timer_dial.value()
        #print("Timer rate is ", self.timer_rate)
        self.grab_timer = QTimer()
        #        self.grab_timer.timeout.connect(self.on_grab_button)
        self.grab_timer.timeout.connect(self.on_grab_timer_timeout)
        self.grab_timer.start(self.timer_rate * 1000.0)

    def on_grab_timer_timeout(self):
        self.grab_timeout.emit()

    def closeEvent(self, event):
        self.gb_closed.emit()

    def get_width(self):
        return self.width()

    def get_height(self):
        return self.height()
Exemplo n.º 4
0
class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.title = "PyQt5 - QDial"
        self.left = 500
        self.top = 200
        self.width = 200
        self.height = 200
        self.iconName = "_imagens/mouse.ico"

        self.setWindowTitle(self.title)
        self.setWindowIcon(QtGui.QIcon(self.iconName))
        self.setGeometry(self.left, self.top, self.width, self.height)

        vbox = QVBoxLayout()

        self.label = QLabel()
        self.label.setFont(QtGui.QFont("Sanserif", 15))

        self.dial = QDial()
        self.dial.setMinimum(0)
        self.dial.setMaximum(100)
        self.dial.setValue(30)
        self.dial.valueChanged.connect(self.dial_changed)

        vbox.addWidget(self.dial)
        vbox.addWidget(self.label)
        self.setLayout(vbox)

        self.show()

    def dial_changed(self):
        getValue = self.dial.value()
        self.label.setText("Dial changed to " + str(getValue))
Exemplo n.º 5
0
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.title = "Pyqt5 QDial"
        self.top = 500
        self.left = 500
        self.width = 600
        self.height = 200
        self.iconName = "transistor.jpg"
        self.setWindowIcon(QtGui.QIcon(self.iconName))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()

        self.label = QLabel(self)
        self.label.setFont(QtGui.QFont("Sanserif", 15))
        self.dial = QDial()
        self.dial.setMinimum(0)
        self.dial.setMaximum(1000)
        self.dial.setValue(30)
        self.dial.valueChanged.connect(self.dial_changed)
        vbox.addWidget(self.label)
        vbox.addWidget(self.dial)
        self.setLayout(vbox)

        self.show()

    def dial_changed(self):
        getValue = self.dial.value()
        self.label.setText(f'Dial is Changing: {getValue}')
Exemplo n.º 6
0
class Window(QWidget):
    def __init__(self, val):
        super().__init__()

        self.title = "QDial"
        self.top = 100
        self.left = 100
        self.width = 400
        self.height = 120
        self.iconName = "logo.png"

        self.setWindowTitle(self.title)
        self.setWindowIcon(QtGui.QIcon(self.iconName))
        self.setGeometry(self.left, self.top, self.width, self.height)

        vbox = QVBoxLayout()

        self.label = QLabel(self)
        self.label.setFont(QtGui.QFont("Elephant", 10))

        self.dial = QDial()
        self.dial.setMinimum(0)
        self.dial.setMaximum(100)
        self.dial.setValue(30)
        self.dial.valueChanged.connect(self.dial_change)

        vbox.addWidget(self.dial)
        vbox.addWidget(self.label)
        self.setLayout(vbox)

        self.show()

    def dial_change(self):
        getvalue = self.dial.value()
        self.label.setText("Dial is changed to " + str(getvalue))
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)
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 Dial"
        self.left = 500
        self.top = 200
        self.width = 300
        self.height = 250
        self.iconName = "icon.png"

        self.setWindowIcon(QtGui.QIcon(self.iconName))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()

        self.dial = QDial()
        self.dial.setMinimum(0)
        self.dial.setMaximum(100)
        self.dial.setValue(30)
        self.dial.valueChanged.connect(self.dial_changed)
        vbox.addWidget(self.dial)

        self.label = QLabel()
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setFont(QtGui.QFont('Sanserif', 14))
        vbox.addWidget(self.label)

        self.setLayout(vbox)
        self.show()

    def dial_changed(self):
        dialValue = self.dial.value()
        self.label.setText("Currerent Value is : {}".format(dialValue))
Exemplo n.º 9
0
class MyWindow(QWidget):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.initGUI("PyQt5 学习 QDial")

        mainLayout = QGridLayout()
        self.setLayout(mainLayout)

        self.dial = QDial()
        self.dial.setMinimum(0)
        self.dial.setMaximum(100)
        self.dial.setValue(50)
        # 最好不要启用 setNotchTarget(),因为默认样式就挺好的
        # self.dial.setNotchTarget(10)
        self.dial.setNotchesVisible(True)
        self.dial.setWrapping(False)

        self.dial.sliderPressed.connect(self.on_slider_pressed_func)
        self.dial.sliderReleased.connect(self.on_slider_released_func)
        self.dial.sliderMoved.connect(self.on_slider_moved_func)
        self.dial.valueChanged.connect(self.on_value_changed)

        mainLayout.addWidget(self.dial, 0, 0, 1, 1)

    def on_slider_pressed_func(self):
        print("Dial --- Pressed")

    def on_slider_released_func(self):
        print("Dial --- Released @ %d" % (self.dial.value()))

    def on_slider_moved_func(self, value):
        print("Dial move to value = %d" % (value))

    def on_value_changed(self):
        print("Current dial value: %i" % (self.dial.value()))

    def initGUI(self, title):
        """
        设置窗口大小和位置,以及标题
        """
        startx = 800
        starty = 400
        width = 480
        height = 320
        self.setGeometry(startx, starty, width, height)
        self.setWindowTitle(title)
Exemplo n.º 10
0
class ModDial(QWidget):
    def __init__(self, label):
        super().__init__()
        self.name = label
        self.qw = QDial()

    def getValue(self):
        return self.qw.value()
Exemplo n.º 11
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.º 12
0
class LightChannel(QWidget):
	changed = pyqtSignal(object)
	def __init__(self, parent, update_callback):
		QWidget.__init__(self, parent)
		self.layout = QGridLayout()
		self.setLayout(self.layout)
		self.update_callback = update_callback


		self.light_value = QSlider(self)
		self.hue_value = QDial(self)
		self.saturation_value = QDial(self)
		self.monitor = Monitor(self)

		self.layout.addWidget(QLabel('Hue'), 0, 0, Qt.AlignHCenter)
		self.layout.addWidget(self.hue_value, 1, 0, Qt.AlignHCenter)
		self.layout.addWidget(QLabel('Saturation'), 2, 0, Qt.AlignHCenter)
		self.layout.addWidget(self.saturation_value, 3, 0, Qt.AlignHCenter)
		self.layout.addWidget(self.monitor, 4, 0, Qt.AlignHCenter)
		self.layout.addWidget(QLabel('Intensity'), 5, 0, Qt.AlignHCenter)
		self.layout.addWidget(self.light_value, 6, 0, Qt.AlignHCenter)

		self.update()

		self.hue_value.valueChanged.connect(self.update)
		self.saturation_value.valueChanged.connect(self.update)
		self.light_value.valueChanged.connect(self.update)


	def get_rgb(self):
		saturation = self.saturation_value.value()/99.0
		light = self.light_value.value()/99.0
		hue = self.hue_value.value()/99.0

		return colorsys.hsv_to_rgb(hue, saturation, light)

	def update(self):
		r, g, b = self.get_rgb()
		self.monitor.setColor(r, g, b)
		self.update_callback.setColor(r, g, b)
		self.changed.emit(self)
Exemplo n.º 13
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.º 14
0
class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QDial Demo")
        self.setGeometry(300, 300, 500, 500)

        self.dial = QDial()
        self.dial.setMaximum(100)
        self.dial.setMinimum(0)
        self.dial.setValue(0)
        self.dial.valueChanged.connect(self.print_dial_value)

        self.label = QLabel("Dial Value is " + str(self.dial.value()))
        self.label.setFont(QFont("Open Sans", 20))

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.dial)
        self.layout.addWidget(self.label)

        self.setLayout(self.layout)

    def print_dial_value(self):
        self.label.setText("Dial Value is " + str(self.dial.value()))
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
class Dial_Box(QtGui.QWidget):

    def __init__(self, idx, unique_ADC_name, dial_name, layout='horizontal'):
        super().__init__()
        self.idx = idx
        self.unique_ADC_name = unique_ADC_name
        if layout == "horizontal":
            self.layout = QtGui.QHBoxLayout()
        else:
            self.layout = QtGui.QVBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(2)

        self.frame = QFrame()
        self.frame.setLayout(self.layout)
        #self.frame.setStyleSheet("border:0px solid rgb(200, 200, 200); ")

        self.dial= QDial()
        self.label = QLabel(dial_name)
        self.box = QSpinBox()

        self.label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)

        self.layout.addWidget(self.label)
        self.layout.addWidget(self.dial)
        self.layout.addWidget(self.box)

        self.dial.valueChanged.connect(self.value_change_dial)
        self.box.valueChanged.connect(self.value_change_box)
        """If unique_ADC_name is None it means that the certain channel
        is no enabled therefore the widget is disabled"""
        if(unique_ADC_name is None):
            self.frame.setEnabled(False)

    def value_change_dial(self):
        pass

    def value_change_box(self):
        pass

    def set_value(self, value):
        pass

    def get_value(self):
        return self.dial.value()
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
    def addDial(self, title, x, y, w, h, labelX, minimum, maximum, key):

        label = QLabel(self.window)
        label.setText(title)
        label.setGeometry(labelX, y + h, w, 20)

        dial = QDial(self.window)
        dial.setGeometry(x, y, w, h)
        dial.setMinimum(minimum)
        dial.setMaximum(maximum)
        dial.valueChanged.connect(lambda: self.updateDial(dial))

        valueLabel = QLabel(self.window)
        valueLabel.setText(str(dial.value()))
        valueLabel.setGeometry(
            dial.geometry().x() + int(dial.geometry().width() / 2) - 5, y - 35,
            w, h)

        self.dialList.append([key, dial, label, valueLabel])
Exemplo n.º 19
0
class Window(QDialog):
    def __init__(self, val):
        super().__init__()

        self.title = "QDial"
        self.left = 300
        self.top = 100
        self.width = 500
        self.height = 500
        self.IconName = "Icon/python.png"
        self.color = 'red'
        self.val = val

        self.InitWindow()

    def InitWindow(self):
        self.setWindowIcon(QtGui.QIcon(self.IconName))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        #self.setStyleSheet('background-color:green')

        vbox = QVBoxLayout()

        self.dial = QDial()
        self.dial.setMinimum(0)
        self.dial.setMaximum(100)
        self.dial.setValue(30)
        self.dial.valueChanged.connect(self.DialChange)

        self.label = QLabel(self)
        self.label.setFont(QtGui.QFont("Sanserif", 15))

        vbox.addWidget(self.dial)
        vbox.addWidget(self.label)

        self.setLayout(vbox)
        self.show()

    def DialChange(self):
        getValue = self.dial.value()
        self.label.setText("Dial Value : " + str(getValue))
Exemplo n.º 20
0
class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.title = "This is first thing"
        self.height = 700
        self.width = 1100
        self.top = 100
        self.left = 200
        self.iconName = "plioky.ico"
        self.dial = QDial()
        self.label = QLabel(self)

        self.init_window()

    def init_window(self):

        self.setWindowIcon(QtGui.QIcon(self.iconName))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        vbox = QVBoxLayout()

        self.label.setFont(QtGui.QFont("Sanserif", 50))
        self.dial.valueChanged.connect(self.dial_changed)
        self.dial.setMinimum(0)
        self.dial.setMaximum(100)
        self.dial.setValue(0)

        vbox.addWidget(self.dial)
        vbox.addWidget(self.label)
        self.setLayout(vbox)

        self.show()

    def dial_changed(self):
        size = self.dial.value()
        self.label.setText(str(size))
Exemplo n.º 21
0
class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.title = "PyQt QDial"
        self.top = 100
        self.left = 100
        self.width = 400
        self.height = 300

        self.vbox = QVBoxLayout()
        self.dial = QDial()
        self.label = QLabel(self)

        self.InitWindow()

    def InitWindow(self):
        self.setWindowIcon(QtGui.QIcon("home.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.Dial()
        self.setLayout(self.vbox)

        self.show()

    def Dial(self):
        self.dial.setMinimum(0)
        self.dial.setMaximum(100)
        self.dial.setValue(30)
        self.dial.valueChanged.connect(self.dial_changed)
        self.vbox.addWidget(self.dial)
        self.vbox.addWidget(self.label)

    def dial_changed(self):
        val = self.dial.value()
        self.label.setText("Dial value is: " + str(val))
Exemplo n.º 22
0
class Image(QWidget):
    def __init__(self, image_path):
        super().__init__()
        self.title = "Image Processing"
        self.left = 10
        self.top = 10
        self.width = 500
        self.height = 250
        self.thresh_type = "cv2.THRESH_BINARY"
        self.image_path = image_path
        self.image = cv2.imread(self.image_path)
        self.image_gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
        self.dial1 = QDial(self)
        self.dial2 = QDial(self)
        self.im_label = QLabel(self)
        self.cb1 = QComboBox(self)
        self.cb2 = QComboBox(self)
        self.label1 = QLabel(self)
        self.label2 = QLabel(self)
        self.reset_button = QPushButton("Revert changes", self)

        self.updateImage(self.image_gray)
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.dial1.setMinimum(0)
        self.dial1.setMaximum(255)
        self.dial2.setMinimum(0)
        self.dial2.setMaximum(255)
        self.dial1.move(20, 130)
        self.dial2.move(120, 130)
        self.dial1.valueChanged.connect(self.dial1_changed)
        self.dial2.valueChanged.connect(self.dial2_changed)

        self.cb1.addItems(
            ["BINARY", "BINARY_INV", "TRUNC", "TOZERO", "TOZERO_INV"])
        self.cb1.activated[str].connect(self.combo1_selection)
        self.cb1.move(40, 50)
        self.cb2.move(280, 50)

        self.reset_button.move(280, 170)
        self.reset_button.clicked.connect(self.revert_button_pressed)

        self.label1.setText("000")
        self.label2.setText("000")
        self.label1.move(60, 120)
        self.label2.move(160, 120)

        self.show()

    def thresh(self):
        _, temp = cv2.threshold(self.image_gray, self.dial1.value(),
                                self.dial2.value(), eval(self.thresh_type))
        self.updateImage(temp)

    def updateImage(self, gray):
        cv2.imshow('image', gray)

    def dial1_changed(self):
        self.thresh()
        self.change_labels()

    def dial2_changed(self):
        self.thresh()
        self.change_labels()

    def combo1_selection(self, text):
        self.thresh_type = "cv2.THRESH_" + text
        self.thresh()

    def revert_button_pressed(self):
        cv2.imshow('image', self.image_gray)
        self.dial1.setValue(0)
        self.dial2.setValue(0)

    def change_labels(self):
        self.label1.setText(str(self.dial1.value()))
        self.label2.setText(str(self.dial2.value()))
Exemplo n.º 23
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.º 24
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.º 25
0
class InstrumentTab(QWidget):
    INSTRUMENT_INDEX = 0

    def __init__(self):
        super().__init__()
        self.instrument = MusicalInstrument()
        self.chord = chord()
        self.initUI()
        self.bindEvent()

    def initUI(self):
        self.layout = QVBoxLayout()
        # 往上对齐
        self.layout.setAlignment(Qt.AlignTop)

        # 查询条件
        self.hbox = QGridLayout()
        self.hbox.setSpacing(1)

        # 和弦/音阶选择条件区域
        rootLabel = QLabel('根音')
        self.rootCombo = QComboBox()
        self.rootCombo.addItems(self.instrument.roots)
        self.rootCombo.setMinimumWidth(100)
        proLabel = QLabel('三音')
        self.proCombo = QComboBox()
        self.proCombo.addItems(self.instrument.pros)
        self.proCombo.setMinimumWidth(100)
        intervelLabel = QLabel('五音')
        self.intervelCombo = QComboBox()
        self.intervelCombo.addItems(self.instrument.intervals)
        self.intervelCombo.setMinimumWidth(100)
        self.mode = 0  # 0:scale mode ; 1:chord mode
        self.scaCheck = QRadioButton('音阶')
        self.scaCheck.setChecked(True)
        self.chordCheck = QRadioButton('和弦')
        scaleLabel = QLabel('音阶')
        self.scaleCombo = QComboBox()
        self.scaleCombo.addItems(self.instrument.scales)
        self.scaleCombo.setMinimumWidth(100)

        commonBox = QGroupBox('音阶/和弦')
        commonBox.setStyleSheet(
            "QGroupBox{ border: 1px groove grey; border-radius:5px;border-style: outset;}"
        )
        commonLayout = QGridLayout()
        commonBox.setLayout(commonLayout)
        commonLayout.addWidget(self.scaCheck, 0, 0)
        commonLayout.addWidget(self.chordCheck, 0, 1)
        commonLayout.addWidget(scaleLabel, 0, 2)
        commonLayout.addWidget(self.scaleCombo, 0, 3, 1, 3)
        commonLayout.addWidget(rootLabel, 1, 0)
        commonLayout.addWidget(self.rootCombo, 1, 1)
        commonLayout.addWidget(proLabel, 1, 2)
        commonLayout.addWidget(self.proCombo, 1, 3)
        commonLayout.addWidget(intervelLabel, 1, 4)
        commonLayout.addWidget(self.intervelCombo, 1, 5)

        # 控制条件区域
        self.fretLabel = QLabel('品数')
        self.guitarSlider = QDial()
        self.guitarSlider.setNotchesVisible(True)
        self.guitarSlider.setMaximumHeight(60)
        self.guitarSlider.setToolTip('21')
        self.guitarSlider.setMinimum(12)
        self.guitarSlider.setMaximum(24)
        self.guitarSlider.setValue(21)
        # piano
        self.pianoSlider = QDial()
        self.pianoSlider.setNotchesVisible(True)
        self.pianoSlider.setMaximumHeight(60)
        self.pianoSlider.setToolTip('4')
        self.pianoSlider.setMinimum(3)
        self.pianoSlider.setMaximum(7)
        self.pianoSlider.setValue(4)
        self.pianoSlider.hide()

        self.speedLabel = QLabel('播放速度')
        self.speedSlider = QDial()
        self.speedSlider.setNotchesVisible(True)
        self.speedSlider.setMaximumHeight(60)
        self.speedLabel.setToolTip('4')
        self.speedSlider.setMinimum(1)
        self.speedSlider.setMaximum(6)
        self.speedSlider.setValue(4)
        self.speed = 0.25

        instLabel = QLabel('音色')
        self.guitarInstCheck = QComboBox()
        self.guitarInstCheck.addItems(
            list(self.instrument.programs[24:31]
                 ))  # Arachno SoundFont - Version 1.0     024~030

        self.pianoInstCheck = QComboBox()
        self.pianoInstCheck.addItems(
            list(self.instrument.programs[:7]
                 ))  # Arachno SoundFont - Version 1.0     0~6
        self.pianoInstCheck.hide()

        pos = ['-', 'C', 'A', 'G', 'E', 'D', '3-note-per-string']
        self.posLabel = QLabel('把位')
        self.posCombo = QComboBox()
        self.posCombo.addItems(pos)
        self.posCombo.setMinimumWidth(100)

        controlBox = QGroupBox('控制')
        controlBox.setStyleSheet(
            "QGroupBox{ border: 1px groove grey; border-radius:5px;border-style: outset;}"
        )
        self.controlLayout = QGridLayout()
        controlBox.setLayout(self.controlLayout)
        self.controlLayout.addWidget(self.guitarSlider, 0, 0)
        self.controlLayout.addWidget(self.fretLabel, 1, 0)
        self.controlLayout.addWidget(self.speedSlider, 0, 1)
        self.controlLayout.addWidget(self.speedLabel, 1, 1)
        self.controlLayout.addWidget(instLabel, 0, 2)
        self.controlLayout.addWidget(self.guitarInstCheck, 0, 3)
        self.controlLayout.addWidget(self.posLabel, 1, 2)
        self.controlLayout.addWidget(self.posCombo, 1, 3)

        self.generateBtn = QPushButton('生成')
        self.generateBtn.setMaximumWidth(100)
        self.generateBtn.setStyleSheet(
            "QPushButton{border:1px groove grey;border-radius:5px;border-style:outset; min-height:40px;}"
        )
        self.playBtn = QPushButton('播放')
        self.playBtn.setMaximumWidth(100)
        self.playBtn.setStyleSheet(
            "QPushButton{border:1px groove grey;border-radius:5px;border-style:outset;min-height:40px;}"
        )

        self.hbox.addWidget(commonBox, 0, 0, 2, 1)
        self.hbox.addWidget(controlBox, 0, 2, 2, 1)
        self.hbox.addWidget(self.generateBtn, 0, 3)
        self.hbox.addWidget(self.playBtn, 1, 3)
        self.hbox.addWidget(QWidget(), 0, 4, 2, 1)  # 占位

        # 垂直布局
        self.layout.addLayout(self.hbox)
        self.tabBox = QTabWidget()
        self.panels = InstrumentPanel(self.instrument).createInstrumentPanel(
            ['Guitar', 'Piano'])
        for pn in self.panels:
            self.tabBox.addTab(pn, pn.name)

        self.switchMode()
        self.layout.addWidget(self.tabBox)
        self.setLayout(self.layout)

    def bindEvent(self):
        self.guitarSlider.valueChanged[int].connect(self.reDrawInstrument)
        self.pianoSlider.valueChanged[int].connect(self.reDrawInstrument)
        self.speedSlider.valueChanged[int].connect(self.switchSpeed)
        self.generateBtn.clicked.connect(self.reDrawInstrument)
        self.scaCheck.toggled.connect(self.switchMode)
        self.chordCheck.toggled.connect(self.switchMode)
        self.guitarInstCheck.currentTextChanged.connect(self.changeProgram)
        self.pianoInstCheck.currentTextChanged.connect(self.changeProgram)
        self.playBtn.clicked.connect(self.playSound)
        self.tabBox.currentChanged.connect(self.activeInstrument)

    # change the current instrument panel,show or hide the corresponding widget
    def activeInstrument(self, value):
        self.INSTRUMENT_INDEX = value
        if self.INSTRUMENT_INDEX == 0:  # GUITAR
            self.pianoSlider.hide()
            self.guitarSlider.show()
            self.pianoInstCheck.hide()
            self.guitarInstCheck.show()
            self.controlLayout.replaceWidget(self.pianoSlider,
                                             self.guitarSlider)
            self.controlLayout.replaceWidget(self.pianoInstCheck,
                                             self.guitarInstCheck)
            self.posLabel.setEnabled(True)
            self.posCombo.setEnabled(True)
            self.fretLabel.setText('品数')
        elif self.INSTRUMENT_INDEX == 1:  # PIANO
            self.pianoSlider.show()
            self.guitarSlider.hide()
            self.pianoInstCheck.show()
            self.guitarInstCheck.hide()
            self.controlLayout.replaceWidget(self.guitarSlider,
                                             self.pianoSlider)
            self.controlLayout.replaceWidget(self.guitarInstCheck,
                                             self.pianoInstCheck)
            self.posLabel.setEnabled(False)
            self.posCombo.setEnabled(False)
            self.fretLabel.setText('八度')

    def reDrawInstrument(self):
        notes = self.getNotes()

        if self.panels[self.INSTRUMENT_INDEX].name == 'Guitar':
            freStr = 'Fret num [' + str(self.guitarSlider.value()) + ']'
            self.guitarSlider.setToolTip(str(self.guitarSlider.value()))
            fretPosition = '\r\n[Guitar board position] POSITION ' + self.posCombo.currentText(
            )
            sound = self.guitarInstCheck.currentText()
            if len(notes) > 1:
                notes1 = []
                for note in notes:
                    notes1.append(note.split('-')[0])
                mode = self.scaleCombo.currentText() if self.mode == 0 else '-'
                self.panels[self.INSTRUMENT_INDEX].initPanel(
                    int(self.guitarSlider.value()), notes1, mode,
                    self.posCombo.currentText())
        elif self.panels[self.INSTRUMENT_INDEX].name == 'Piano':
            freStr = 'Octave num [' + str(self.pianoSlider.value()) + ']'
            self.pianoSlider.setToolTip(str(self.pianoSlider.value()))
            fretPosition = ''
            sound = self.pianoInstCheck.currentText()
            if len(notes) > 1:
                self.panels[self.INSTRUMENT_INDEX].initPanel(
                    int(self.pianoSlider.value()), notes)
        else:
            pass

        infoStr = '[Instrument] ' + self.panels[self.INSTRUMENT_INDEX].name
        infoStr = infoStr + '\r\n[Program] ' + sound
        infoStr = infoStr + '\r\n[Scope] ' + freStr
        infoStr = infoStr + '\r\n[Note mode] ' + ('scale' if self.mode == 0
                                                  else 'chord')
        infoStr = infoStr + '\r\n[Key] ' + notes[0]
        infoStr = infoStr + '\r\n[Notes] ' + str(notes)
        infoStr = infoStr + fretPosition
        infoStr = infoStr + '\r\n[Speed] ' + str(self.speed) + ' seconds'
        self.panels[self.INSTRUMENT_INDEX].detail.setText(infoStr)

    def switchMode(self):
        self.mode = self.scaCheck.isChecked()
        self.mode = self.chordCheck.isChecked()
        if self.mode == 0:  # scale
            self.scaCheck.setChecked(True)
            self.chordCheck.setChecked(False)
            self.scaleCombo.setEnabled(True)
            self.proCombo.setEnabled(False)
            self.intervelCombo.setEnabled(False)
        else:  # chord
            self.scaCheck.setChecked(False)
            self.chordCheck.setChecked(True)
            self.scaleCombo.setEnabled(False)
            self.proCombo.setEnabled(True)
            self.intervelCombo.setEnabled(True)

    def switchSpeed(self, value):
        sp = {1: 1, 2: 0.75, 3: 0.5, 4: 0.25, 5: 0.1, 6: 0.05}
        self.speed = sp.get(value)
        self.speedSlider.setToolTip(str(self.speed))

    # change instrument's program
    def changeProgram(self, value):
        self.panels[self.INSTRUMENT_INDEX].changeProgram(value)

    # play a note or chord
    def playSound(self):
        notes = self.getNotes()
        if len(notes) > 1:
            self.panels[self.INSTRUMENT_INDEX].playArpeggio(notes, self.speed)

    # get all notes
    def getNotes(self):
        if self.mode == 0:  # scale
            notes = list(
                self.chord.getScales(self.rootCombo.currentText(),
                                     self.scaleCombo.currentText()).values())
        else:  # chord
            notes = list(
                self.chord.getChord(self.rootCombo.currentText(),
                                    self.proCombo.currentText(),
                                    self.intervelCombo.currentText()).values())
        return notes
Exemplo n.º 26
0
class MainGUI(QDialog):
    def __init__(self, parent=None, imageoperator=None):
        super(MainGUI, self).__init__(parent)

        self.inputfile = None
        self.batchfilenames = None

        self.imageoperator = imageoperator

        self.originalPalette = QApplication.palette()

        self.btnFileOpen = QPushButton("Choose image file...")
        self.btnFileOpen.clicked.connect(self.getfile)

        self.leInputImage = QLabel()
        self.leInputImage.setPixmap(
            QPixmap(
                os.path.abspath(
                    os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 '..', '..', '..', 'resources',
                                 'emptyspace.png'))).scaledToHeight(400))

        self.leOutputImage = QLabel()
        self.leOutputImage.setPixmap(
            QPixmap(
                os.path.abspath(
                    os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 '..', '..', '..', 'resources',
                                 'emptyspace.png'))).scaledToHeight(400))

        self.createBottomLeftTabWidget()
        self.createBottomRightTabWidget()
        self.createProgressBar()

        # Top row of GUI, with image displays
        topLeftLayout = QGroupBox("Input Image")
        layout = QVBoxLayout()
        layout.addWidget(self.leInputImage)
        layout.addWidget(self.btnFileOpen)
        layout.addStretch(1)
        topLeftLayout.setLayout(layout)

        topRightLayout = QGroupBox("Output Image")
        layout = QVBoxLayout()
        layout.addWidget(self.leOutputImage)
        layout.addStretch(1)
        topRightLayout.setLayout(layout)

        topLayout = QHBoxLayout()
        topLayout.addWidget(topLeftLayout)
        topLayout.addWidget(topRightLayout)

        # Bottom row of GUI, with processing functions
        bottomLeftLayout = QGroupBox("Processing")
        layout = QVBoxLayout()
        layout.addWidget(self.bottomLeftTabWidget)
        layout.addStretch(1)
        bottomLeftLayout.setLayout(layout)

        bottomRightLayout = QGroupBox("Results")
        layout = QVBoxLayout()
        layout.addWidget(self.bottomRightTabWidget)
        layout.addStretch(1)
        bottomRightLayout.setLayout(layout)

        bottomLayout = QHBoxLayout()
        bottomLayout.addWidget(bottomLeftLayout)
        bottomLayout.addWidget(bottomRightLayout)

        mainLayout = QGridLayout()
        mainLayout.addLayout(topLayout, 0, 0, 1, 2)
        mainLayout.addLayout(bottomLayout, 1, 0, 1, 2)
        mainLayout.addWidget(self.bottomLeftTabWidget, 1, 0)
        mainLayout.addWidget(self.bottomRightTabWidget, 1, 1)
        mainLayout.addWidget(self.progressBar, 3, 0, 1, 2)
        mainLayout.setRowStretch(0, 1)
        mainLayout.setRowStretch(1, 1)
        mainLayout.setRowMinimumHeight(1, 200)
        mainLayout.setColumnStretch(0, 1)
        mainLayout.setColumnStretch(1, 1)
        self.setLayout(mainLayout)

        self.setWindowTitle("Pituitary Cytokeratin Spatial Frequency")
        QApplication.setStyle(QStyleFactory.create('Fusion'))
        QApplication.setPalette(QApplication.style().standardPalette())

    def createBottomLeftTabWidget(self):

        self.bottomLeftTabWidget = QTabWidget()
        self.bottomLeftTabWidget.setSizePolicy(QSizePolicy.Preferred,
                                               QSizePolicy.Ignored)

        tab1 = QWidget()
        self.btnProcess = QPushButton("Process!")
        self.btnProcess.setStyleSheet(
            "font: bold;background-color: green;font-size: 36px;height: 48px;width: 300px;"
        )
        self.btnProcess.clicked.connect(self.processInputImage)

        self.dial = QDial()
        self.dial.setMinimum(1)
        self.dial.setMaximum(20)
        self.dial.setValue(6)
        self.dial.setSingleStep(1)
        self.dial.setNotchesVisible(True)
        self.dial.valueChanged.connect(self.handleDialMove)

        self.SpaceConstLabel = QLabel()
        self.SpaceConstLabel.setText("Space Constant: " +
                                     str(self.dial.value()))

        tab1hbox = QHBoxLayout()
        tab1hbox.setContentsMargins(5, 5, 5, 5)
        tab1hbox.addStretch(0)
        tab1hbox.addWidget(self.btnProcess)
        tab1hbox.addStretch(0)
        tab1hbox.addWidget(self.dial)
        tab1hbox.addWidget(self.SpaceConstLabel)
        tab1hbox.addStretch(0)
        tab1.setLayout(tab1hbox)

        tab2 = QWidget()
        self.batchTableWidget = QTableWidget(10, 1)
        self.batchTableWidget.setHorizontalHeaderLabels(["Filename"])
        header = self.batchTableWidget.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Stretch)

        tab2hbox = QHBoxLayout()
        tab2hbox.setContentsMargins(5, 5, 5, 5)
        tab2hbox.addWidget(self.batchTableWidget)
        self.buttonBatchLoad = QPushButton("Load Files")
        self.buttonBatchLoad.clicked.connect(self.handleBatchLoad)
        tab2hbox.addWidget(self.buttonBatchLoad)
        tab2.setLayout(tab2hbox)

        self.bottomLeftTabWidget.addTab(tab1, "&Processing")
        self.bottomLeftTabWidget.addTab(tab2, "&Batch")

    def createBottomRightTabWidget(self):
        self.bottomRightTabWidget = QTabWidget()
        self.bottomRightTabWidget.setSizePolicy(QSizePolicy.Preferred,
                                                QSizePolicy.Ignored)

        tab1 = QWidget()
        self.tableWidget = QTableWidget(10, 2)
        self.tableWidget.setHorizontalHeaderLabels(
            ["Filename", "Density Index"])
        header = self.tableWidget.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Stretch)
        header.setSectionResizeMode(1, QHeaderView.ResizeToContents)

        self.TableRowCursor = 0

        tab1hbox = QHBoxLayout()
        tab1hbox.setContentsMargins(5, 5, 5, 5)
        tab1hbox.addWidget(self.tableWidget)

        self.buttonSave = QPushButton("Save CSV")
        self.buttonSave.clicked.connect(self.handleSave)
        tab1hbox.addWidget(self.buttonSave)
        tab1.setLayout(tab1hbox)

        tab2 = QWidget()
        textEdit = QTextEdit()

        textEdit.setPlainText(
            "The Magi\n"
            "W. B. Yeats - 1865-1939\n"
            "\n"
            "Now as at all times I can see in the mind's eye,\n"
            "In their stiff, painted clothes, the pale unsatisfied ones\n"
            "Appear and disappear in the blue depth of the sky\n"
            "With all their ancient faces like rain-beaten stones,\n"
            "And all their helms of silver hovering side by side,\n"
            "And all their eyes still fixed, hoping to find once more,\n"
            "Being by Calvary's turbulence unsatisfied,\n"
            "The uncontrollable mystery on the bestial floor.\n")

        tab2hbox = QHBoxLayout()
        tab2hbox.setContentsMargins(5, 5, 5, 5)
        tab2hbox.addWidget(textEdit)
        tab2.setLayout(tab2hbox)

        self.bottomRightTabWidget.addTab(tab1, "&Results")
        self.bottomRightTabWidget.addTab(tab2, "Free &Text")

    def createProgressBar(self):
        self.progressBar = QProgressBar()
        self.progressBar.setRange(0, 10000)
        self.progressBar.setValue(0)

    def advanceProgressBar(self):
        curVal = self.progressBar.value()
        maxVal = self.progressBar.maximum()
        self.progressBar.setValue(curVal + (maxVal - curVal) / 100)

    def getfile(self):
        self.inputfname = QFileDialog.getOpenFileName(self, 'Open file', '~',
                                                      "Image files (*.*)")
        if os.path.isfile(self.inputfname[0]):
            self.inputfile = self.inputfname[0]
            self.leInputImage.setPixmap(
                QPixmap(self.inputfile).scaledToHeight(400))

    def handleDialMove(self):
        self.SpaceConstLabel.setText("Space Constant: " +
                                     str(self.dial.value()))

    def handleBatchLoad(self):
        userlist = QFileDialog.getOpenFileNames(self, 'Open file', '~',
                                                "Image files (*.*)")
        self.batchfilenames = userlist[0]
        self.batchTableWidget.setRowCount(len(self.batchfilenames))
        self.batchTableWidget.clear()
        for row in range(len(self.batchfilenames)):
            self.inputfile = None
            self.batchTableWidget.setItem(
                row - 1, 1,
                QTableWidgetItem(os.path.basename(self.batchfilenames[row])))

    def processInputImage(self):

        if (self.inputfile):
            filelist = [self.inputfile]
            display_output_image = True
        elif (self.batchfilenames):
            filelist = self.batchfilenames
            display_output_image = False
        else:
            filelist = []
            print("No input file(s) specified!")
            return (0)

        self.imageoperator.setlims([self.dial.value(), 10 * self.dial.value()])

        self.progressBar.setRange(0, len(filelist))
        self.progressBar.setValue(0)
        for row in range(len(filelist)):
            infl = filelist[row]
            r = self.imageoperator.processImage(infl)
            di = r['density_index']

            if (display_output_image):
                imout = np.int8(
                    np.floor(255 * np.stack((r['bpdiffim'], ) * 3, axis=-1)))
                h, w, c = imout.shape
                bytesPerLine = w * 3
                qpix = QPixmap.fromImage(
                    QImage(imout, w, h, bytesPerLine, QImage.Format_RGB888))
                self.leOutputImage.setPixmap(qpix.scaledToHeight(400))

                #print("Density index: {0:.2f}".format(di))

            nr = self.tableWidget.rowCount()
            if nr <= self.TableRowCursor:
                self.tableWidget.insertRow(nr)
            self.tableWidget.setItem(self.TableRowCursor, 0,
                                     QTableWidgetItem(os.path.basename(infl)))
            self.tableWidget.setItem(self.TableRowCursor, 1,
                                     QTableWidgetItem(str(di)))
            self.TableRowCursor = self.TableRowCursor + 1
            self.progressBar.setValue(row + 1)

    def handleSave(self):
        p = QFileDialog.getSaveFileName(self, 'Save File', '', 'CSV(*.csv)')
        path = p[0]
        if len(path):
            with open(path, 'w') as stream:
                writer = csv.writer(stream)
                for row in range(self.tableWidget.rowCount()):
                    rowdata = []
                    emptyrow = True
                    for column in range(self.tableWidget.columnCount()):
                        item = self.tableWidget.item(row, column)
                        if item is not None:
                            rowdata.append(item.text())
                            emptyrow = False
                        else:
                            rowdata.append('')
                    if not emptyrow:
                        writer.writerow(rowdata)
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.º 28
0
class MainWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(0, 0, 1000, 800)
        self.setStyleSheet('background-color:rgb(0, 0, 0)')
        self.setWindowTitle("*****가야금을 연주해보자******")

        #Title text frame
        self.titleFrame = QFrame(self)
        self.titleFrame.setGeometry(QRect(0, 0, 800, 150))
        self.titleFrameLayout = QVBoxLayout(self.titleFrame)

        #set Title font
        self.font = QFont()
        self.font.setFamily("Source Code Pro")
        self.font.setPointSize(35)
        # self.font.setBold(True)
        # self.font.setItalic(True)

        self.l2 = QLabel(self)
        self.l2.setText("Press a Key\nTo Start Playing!")

        self.l2.setFont(self.font)
        self.l2.setStyleSheet('color : white')
        self.titleFrameLayout.addWidget(self.l2, 0, Qt.AlignHCenter)

        #set frame
        self.frame1 = QFrame(self)
        self.frame1.setGeometry(QRect(0, 150, 250, 650))
        # self.frame1.setStyleSheet('background-color:white')
        self.frame1Layout = QVBoxLayout(self.frame1)

        #add buttons for keys
        self.key1 = MyButton(1)
        self.key1.setText("Eb1  (1)")
        self.frame1Layout.addWidget(self.key1, 0, Qt.AlignHCenter)

        self.key2 = MyButton(2)
        self.key2.setText("F1    (2)")
        self.frame1Layout.addWidget(self.key2, 0, Qt.AlignHCenter)

        self.key3 = MyButton(3)
        self.key3.setText("Ab1  (3)")
        self.frame1Layout.addWidget(self.key3, 0, Qt.AlignHCenter)

        self.key4 = MyButton(4)
        self.key4.setText("Bb1  (4)")
        self.frame1Layout.addWidget(self.key4, 0, Qt.AlignHCenter)

        self.key5 = MyButton(5)
        self.key5.setText("Cb1  (5)")
        self.frame1Layout.addWidget(self.key5, 0, Qt.AlignHCenter)

        self.key6 = MyButton(6)
        self.key6.setText("Eb1  (6)")
        self.frame1Layout.addWidget(self.key6, 0, Qt.AlignHCenter)

        self.key7 = MyButton(7)
        self.key7.setText("F2    (7)")
        self.frame1Layout.addWidget(self.key7, 0, Qt.AlignHCenter)

        self.key8 = MyButton(8)
        self.key8.setText("Ab2  (8)")
        self.frame1Layout.addWidget(self.key8, 0, Qt.AlignHCenter)

        self.key9 = MyButton(9)
        self.key9.setText("Bb2  (9)")
        self.frame1Layout.addWidget(self.key9, 0, Qt.AlignHCenter)

        self.key10 = MyButton(10)
        self.key10.setText("C2    (0)")
        self.frame1Layout.addWidget(self.key10, 0, Qt.AlignHCenter)

        self.key11 = MyButton(11)
        self.key11.setText("Eb3   (-)")
        self.frame1Layout.addWidget(self.key11, 0, Qt.AlignHCenter)

        self.key12 = MyButton(12)
        self.key12.setText("F3    (+)")
        self.frame1Layout.addWidget(self.key12, 0, Qt.AlignHCenter)

        self.volumeUI()

    #     self.stringColor(bool)
    #
    # def stringColor(self, enabled):
    #
    #     self.pen1 = QPen()
    #     self.pen1.setColor(Qt.white)
    #     self.pen1.setWidth(2)
    #
    #     self.pen2 = QPen()
    #     self.pen2.setColor(Qt.red)
    #     self.pen2.setWidth(2)
    #
    #     self.pen = QPen()
    #     if enabled == True:
    #         self.pen = self.pen2
    #     else:
    #         self.pen = self.pen1

    def paintEvent(self, event):
        self.pen1 = QPen()
        self.pen1.setColor(Qt.white)
        self.pen1.setWidth(1)

        # self.pen2 = QPen()
        # self.pen2.setColor(Qt.red)
        # self.pen2.setWidth(2)
        p = QPainter(self)

        p.setPen(self.pen1)

        for i in range(12):
            p.drawEllipse(255 + 40 * i, 180 + 50 * i, 5, 40)
            p.drawLine(250, 200 + 50 * i, 700, 200 + 50 * i)

    def volumeUI(self):
        # Title text
        self.titleFrame2 = QFrame(self)
        self.titleFrame2.setGeometry(QRect(800, 0, 200, 150))
        self.titleFrame2.setStyleSheet('background-color:rgb(239, 49, 141)')
        self.titleFrame2Layout = QVBoxLayout(self.titleFrame2)

        self.l2 = QLabel()
        self.l2.setText("Adjust\nVolume.")
        self.l2.setFont(self.font)
        self.l2.setStyleSheet('color:black')
        self.titleFrame2Layout.addWidget(self.l2, 0, Qt.AlignHCenter)

        # frame3
        self.frame = QFrame(self)
        self.frame.setGeometry(QRect(800, 150, 200, 650))
        self.frame.setStyleSheet('background-color:rgb(239, 49, 141)')
        self.frameLayout = QVBoxLayout(self.frame)

        # VolumeDial
        self.volumeDial = QDial(self)
        self.volumeDial.setStyleSheet('background-color:white')
        self.volumeDial.setWrapping(True)
        self.frameLayout.addWidget(self.volumeDial)

        # VolumeBar
        self.volumeBar = QProgressBar(self)
        self.volumeBar.setProperty("value", 0)
        self.volumeBar.setOrientation(Qt.Vertical)
        self.frameLayout.addWidget(self.volumeBar, 0, Qt.AlignHCenter)

        # dial connect to bar
        self.volumeDial.valueChanged['int'].connect(self.volumeBar.setValue)
        self.volumeDial.setValue(10)

        # volume label
        self.l3 = QLabel()
        self.l3.setFont(self.font)
        self.l3.setText(str(self.volumeDial.value()))
        self.l3.setStyleSheet('color:black')
        self.frameLayout.addWidget(self.l3, 0, Qt.AlignHCenter)

        mixer.init()
        self.setChannel()

        for i in range(12):
            mixer.Channel(i).set_volume(0.1)

        # connect volume dial to sound volume
        self.volumeDial.valueChanged['int'].connect(self.setVolume)

    def setVolume(self, value):
        self.value = value
        for i in range(12):
            mixer.Channel(i).set_volume(self.value * 0.01)
            self.l3.setText(str(int(100 * mixer.Channel(i).get_volume())))
        return self.value

    # volume change with up, down key
    def upDownKeyEvent(self, event):
        if event.key() == Qt.Key_Up:
            self.volumeDial.valueChange(1)

        if event.key() == Qt.Key_Down:
            self.volumeDial.valueChange(-1)

    def setChannel(self):
        mixer.set_num_channels(12)

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_1:
            mixer.Channel(0).play(mixer.Sound('Eb1_gayageum.wav'))
            print(mixer.Channel(0).get_volume())
            self.key1.setChecked(True)

        if e.key() == Qt.Key_2:
            mixer.Channel(1).play(mixer.Sound('F1_gayageum.wav'))
            print(mixer.Channel(1).get_volume())
            self.key2.setChecked(True)

        if e.key() == Qt.Key_3:
            mixer.Channel(2).play(mixer.Sound('Ab1_gayageum.wav'))
            print(mixer.Channel(2).get_volume())
            self.key3.setChecked(True)

        if e.key() == Qt.Key_4:
            mixer.Channel(3).play(mixer.Sound('Bb1_gayageum.wav'))
            print(mixer.Channel(3).get_volume())
            self.key4.setChecked(True)

        if e.key() == Qt.Key_5:
            mixer.Channel(4).play(mixer.Sound('C1_gayageum.wav'))
            print(mixer.Channel(4).get_volume())
            self.key5.setChecked(True)

        if e.key() == Qt.Key_6:
            mixer.Channel(5).play(mixer.Sound('Eb2_gayageum.wav'))
            print(mixer.Channel(5).get_volume())
            self.key6.setChecked(True)

        if e.key() == Qt.Key_7:
            mixer.Channel(6).play(mixer.Sound('F2_gayageum.wav'))
            print(mixer.Channel(6).get_volume())
            self.key7.setChecked(True)

        if e.key() == Qt.Key_8:
            mixer.Channel(7).play(mixer.Sound('Ab2_gayageum.wav'))
            print(mixer.Channel(7).get_volume())
            self.key8.setChecked(True)

        if e.key() == Qt.Key_9:
            mixer.Channel(8).play(mixer.Sound('Bb2_gayageum.wav'))
            print(mixer.Channel(8).get_volume())
            self.key9.setChecked(True)

        if e.key() == Qt.Key_0:
            mixer.Channel(9).play(mixer.Sound('C2_gayageum.wav'))
            print(mixer.Channel(9).get_volume())
            self.key10.setChecked(True)

        if e.key() == Qt.Key_Minus:
            mixer.Channel(10).play(mixer.Sound('Eb3_gayageum.wav'))
            print(mixer.Channel(10).get_volume())
            self.key11.setChecked(True)

        if e.key() == Qt.Key_Equal:
            mixer.Channel(11).play(mixer.Sound('F3_gayageum.wav'))
            print(mixer.Channel(11).get_volume())
            self.key12.setChecked(True)
Exemplo n.º 29
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.º 30
0
class dial_4vent(QWidget):
    style ='''
    QDial
    {
        background-color: rgb(255,255,255);
        font: 15px Menlo;
        color: rgb(0, 0, 131);
        /*text-align: left;*/
    }
    QLabel {
        /*border: 1px solid white;*/
        border-radius: 5px;
        background-color:  rgb(172, 236, 217);
        font: 15px Verdana, sans-serif;
        color:  rgb(0, 0, 131);
        text-align: center;
    }
    '''
    def __init__(self, title, min, max, **kwargs):
        super().__init__()
        self.title = title
        self.min   = min;self.max = max; self.moved_cbs = []
        self.layout = QGridLayout()
        self.label0 = QLabel(self)
        self.label  = QLabel(self)
        self.dial   = QDial()
        self.bar    = _Bar(["#5e4fa2", "#3288bd", "#66c2a5", "#abdda4",
                            "#e6f598", "#ffffbf", "#fee08b", "#fdae61",
                            "#f46d43", "#d53e4f", "#9e0142"])
        #_Bar(20) for pink ["#49006a", "#7a0177", "#ae017e", "#dd3497", "#f768a1", "#fa9fb5", "#fcc5c0", "#fde0dd", "#fff7f3"]
        self.label0.setStyleSheet(self.style)
        self.dial.setStyleSheet(self.style)
        self.label.setStyleSheet(self.style)
        self.dial.setMinimum(self.min)
        self.dial.setMaximum(self.max)
        self.dial.setValue(self.max)
        self.dial.setNotchesVisible(True)
        self.dial.valueChanged.connect(self.slider_moved)
        self.dial.setWrapping(False)
        self.dial.setGeometry(QtCore.QRect(25,25,100,100))
        self.layout.addWidget(self.label0, 0, 0, 1, 1)
        self.layout.addWidget(self.dial,1,0,1,1)
        self.layout.addWidget(self.bar,1,1,1,1)
        self.layout.addWidget(self.label,2,0, 1, 1)
        self.setLayout(self.layout)
        self.label0.setText(self.title)
        self.label.setStyleSheet("font-family: Impact, Charcoal, sans-serif");
        self.label.setText(str(self.dial.value()))
        #self.dial.installEventFilter(self) ## disables person using mouse
        self.show()
        ## Bar related initalization
        self.add_slider_moved(self.bar._trigger_refresh)
        # Take NO feedback from click events on the meter.
        self.bar.installEventFilter(self)

    def __getattr__(self, name):
        if name in self.__dict__:
            return self[name]
        return getattr(self.dial, name)

    def eventFilter(self, source, event):
        if (source is self.dial and isinstance(event, (
            QtGui.QMouseEvent, QtGui.QWheelEvent, QtGui.QKeyEvent))):
            return True
        return QtGui.QWidget.eventFilter(self, source, event)

    def slider_moved(self):
        self.label.setText(str(self.dial.value()))
        for fn in self.moved_cbs:
            fn()
    def add_slider_moved(self, func):
        self.moved_cbs.append(func)

    def setColor(self, color):
        self.bar.steps = [color] * self.bar.n_steps
        self.bar.update()

    def setColors(self, colors):
        self.bar.n_steps = len(colors)
        self.bar.steps = colors
        self.bar.update()

    def setBarPadding(self, i):
        self.bar._padding = int(i)
        self.bar.update()

    def setBarSolidPercent(self, f):
        self.bar.bar_solid_percent = float(f)
        self.bar.update()

    def setBackgroundColor(self, color):
        self.bar._background_color = QtGui.QColor(color)
        self.bar.update()
Exemplo n.º 31
0
class SpinnerDialComboWidget(QWidget):
    value_changed = pyqtSignal()

    # name: The string name that will be displayed on top of the widget
    # default_value: The value that will be initially set as the widget's value
    # min_val: The minimum value that will be initially set
    # max_val: The maximum value that will be initially set
    def __init__(self,
                 name="",
                 default_value=0,
                 min_val=0,
                 max_val=100,
                 parent=None):
        QWidget.__init__(self, parent=parent)

        # The minimum value that can be set
        self.min_val = min_val

        # The maximum value that can be set
        self.max_val = max_val

        # The widget's current value
        self.value = default_value

        self.title_label = QLabel(name)

        # The widget's dial
        self.dial = QDial(self)
        self.dial.setSingleStep(1)
        self.dial.setPageStep(1)
        self.dial.setMinimum(min_val)
        self.dial.setMaximum(max_val)
        self.dial.setValue(default_value)
        self.dial.valueChanged.connect(self.on_dial_changed)

        # The widget's spin box
        self.spinner = QSpinBox(self)
        self.spinner.setMinimum(min_val)
        self.spinner.setMaximum(max_val)
        self.spinner.setValue(default_value)
        self.spinner.valueChanged.connect(self.on_spinner_changed)

        self.setup_gui()

    # Sets up the positioning of the UI elements
    def setup_gui(self):
        vertical_layout = QVBoxLayout(self)

        vertical_layout.addStretch(1)
        vertical_layout.addWidget(self.title_label)
        vertical_layout.addWidget(self.spinner)
        vertical_layout.addWidget(self.dial)

    # The callback for when the dial is changes
    @pyqtSlot()
    def on_dial_changed(self):
        self.value = self.dial.value()

        self.spinner.blockSignals(True)

        self.spinner.setValue(self.dial.value())

        self.spinner.blockSignals(False)

        self.value_changed.emit()

    # The callback for when the spin box is changed
    @pyqtSlot()
    def on_spinner_changed(self):
        self.value = self.spinner.value()

        self.dial.blockSignals(True)

        self.dial.setValue(self.spinner.value())

        self.dial.blockSignals(False)

        self.value_changed.emit()

    # Sets the minimum value
    # new_min: The new minimum value to be set
    def set_min(self, new_min):
        if new_min > self.max_val:
            return

        self.min_val = new_min

        self.dial.blockSignals(True)
        self.spinner.blockSignals(True)

        self.spinner.setMinimum(new_min)
        self.dial.setMinimum(new_min)

        self.dial.blockSignals(False)
        self.spinner.blockSignals(False)

        self.value_changed.emit()

    # Sets the maximum value
    # new_max: The new maximum value to be set
    def set_max(self, new_max):
        if new_max < self.min_val:
            return

        self.max_val = new_max

        self.dial.blockSignals(True)
        self.spinner.blockSignals(True)

        self.spinner.setMaximum(new_max)
        self.dial.setMaximum(new_max)

        self.dial.blockSignals(False)
        self.spinner.blockSignals(False)

        self.value_changed.emit()

    # Sets the widget value
    # value: The value to be set
    def set_value(self, value):
        self.value = value

        self.dial.blockSignals(True)
        self.spinner.blockSignals(True)

        self.dial.setValue(value)
        self.spinner.setValue(value)

        self.dial.blockSignals(False)
        self.spinner.blockSignals(False)

        self.value_changed.emit()
Exemplo n.º 32
0
    def setup_tabs(self):
        tab_widget = QTabWidget()

        tab1 = QWidget()
        table = QTableWidget(10, 10)
        tab1_box = QHBoxLayout()
        tab1_box.addWidget(table)
        tab1.setLayout(tab1_box)

        tab2 = QWidget()
        tab2_box = QVBoxLayout()

        tab2_grid = QGridLayout()
        tab2_grid.setSpacing(10)

        line_label = QLabel('Text Field')
        line_edit = QLineEdit()

        slider_label = QLabel('Slider Value: 50')
        slider = QSlider(Qt.Horizontal)
        slider.setValue(50)
        slider.valueChanged[int].connect(lambda: self.change_value('Slider', slider.value(), slider_label))

        dial_label = QLabel('Dial Value: 50')
        dial = QDial()
        dial.setValue(50)
        dial.valueChanged[int].connect(lambda: self.change_value('Dial', dial.value(), dial_label))

        radio_button1 = QRadioButton('Radio Button 1')
        radio_button2 = QRadioButton('Radio Button 2')
        radio_button3 = QRadioButton('Radio Button 3')

        button_label = QLabel('None Selected')

        radio_button1.clicked.connect(lambda: self.radio_button(radio_button1, button_label))
        radio_button2.clicked.connect(lambda: self.radio_button(radio_button2, button_label))
        radio_button3.clicked.connect(lambda: self.radio_button(radio_button3, button_label))

        tab2_grid.addWidget(line_label, 1, 1, 1, 1)
        tab2_grid.addWidget(line_edit, 1, 2, 1, 3)
        tab2_grid.addWidget(slider_label, 2, 1, 1, 1)
        tab2_grid.addWidget(slider, 2, 2, 1, 2)
        tab2_grid.addWidget(dial_label, 3, 1, 1, 1)
        tab2_grid.addWidget(dial, 3, 2, 2, 2)
        tab2_grid.addWidget(button_label, 5, 1, 1, 1)
        tab2_grid.addWidget(radio_button1, 6, 2, 1, 1)
        tab2_grid.addWidget(radio_button2, 7, 2, 1, 1)
        tab2_grid.addWidget(radio_button3, 8, 2, 1, 1)

        tab2_box.addLayout(tab2_grid)
        tab2_box.addStretch()
        tab2.setLayout(tab2_box)

        tab3 = QWidget()
        tab3_box = QVBoxLayout()

        figure, axes = plt.subplots()
        self.canvas = FigureCanvas(figure)

        random_button = QPushButton('Random')
        random_button.clicked.connect(lambda: self.set_graph_values(figure, axes))

        tab3_box.addWidget(random_button)
        tab3_box.addWidget(self.canvas)

        tab3.setLayout(tab3_box)

        tab_widget.addTab(tab1, 'tab 1')
        tab_widget.addTab(tab2, 'tab 2')
        tab_widget.addTab(tab3, 'tab 3')
        self.mainLayout.addWidget(tab_widget)