def __init__(self, *args): super().__init__(BrickletCurrent25, *args) self.cur = self.device self.cbe_current = CallbackEmulator(self.cur.get_current, None, self.cb_current, self.increase_error_count) self.qtcb_over.connect(self.cb_over) self.cur.register_callback(self.cur.CALLBACK_OVER_CURRENT, self.qtcb_over.emit) self.over_label = QLabel('Over Current: No') self.calibrate_button = QPushButton('Calibrate Zero') self.calibrate_button.clicked.connect(self.calibrate_clicked) self.current_current = CurveValueWrapper() # float, A plots = [('Current', Qt.red, self.current_current, format_current)] self.plot_widget = PlotWidget('Current [A]', plots, extra_key_widgets=[self.over_label], y_resolution=0.001) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addWidget(self.calibrate_button)
def __init__(self, settings): super(QWidget, self).__init__() self._layout = QBoxLayout(QBoxLayout.TopToBottom) self.setLayout(self._layout) self.settings = settings # eq directory widget = QWidget() layout = QBoxLayout(QBoxLayout.LeftToRight) widget.setLayout(layout) label = QLabel("Everquest Directory: ") layout.addWidget(label) text = QLineEdit() text.setText(self.settings.get_value("general", "eq_directory")) text.setToolTip(self.settings.get_value("general", "eq_directory")) text.setDisabled(True) self._text_eq_directory = text layout.addWidget(text, 1) button = QPushButton("Browse...") button.clicked.connect(self._get_eq_directory) layout.addWidget(button) self._layout.addWidget(widget, 0, Qt.AlignTop) # eq directory info frame = QFrame() frame.setFrameShadow(QFrame.Sunken) frame.setFrameShape(QFrame.Box) frame_layout = QBoxLayout(QBoxLayout.LeftToRight) frame.setLayout(frame_layout) widget = QWidget() layout = QBoxLayout(QBoxLayout.LeftToRight) widget.setLayout(layout) self._label_eq_directory = QLabel() layout.addWidget(self._label_eq_directory, 1) frame_layout.addWidget(widget, 1, Qt.AlignCenter) self._layout.addWidget(frame, 1) # parse interval widget = QWidget() layout = QBoxLayout(QBoxLayout.LeftToRight) widget.setLayout(layout) label = QLabel("Seconds between parse checks: ") layout.addWidget(label, 0, Qt.AlignLeft) text = QLineEdit() text.setText(str(self.settings.get_value("general", "parse_interval"))) text.editingFinished.connect(self._parse_interval_editing_finished) text.setMaxLength(3) self._text_parse_interval = text metrics = QFontMetrics(QApplication.font()) text.setFixedWidth(metrics.width("888888")) layout.addWidget(text, 0, Qt.AlignLeft) self._layout.addWidget(widget, 0, Qt.AlignTop | Qt.AlignLeft) # spacing at bottom of window widget = QWidget() self._layout.addWidget(widget, 1) # setup if settings.get_value("general", "eq_directory") is not None: self._check_directory_stats()
def class_selected(self): # the .ui is set to 1 selection for index in self.classes.selectionModel().selectedIndexes(): class_name = self.class_model.data(index, Qt.DisplayRole) self.log.debug("Setting class to {0}".format(class_name)) self.enable_all.setToolTip("Include all permissions in the {0} class.".format(class_name)) self.disable_all.setToolTip("Exclude all permissions in the {0} class.".format(class_name)) self._clear_mappings() # populate new mappings for perm in sorted(self.perm_map.perms(class_name)): # create permission mapping mapping = PermissionMapping(self, perm, self.edit) mapping.setAttribute(Qt.WA_DeleteOnClose) self.class_toggle.connect(mapping.enabled.setChecked) self.perm_mappings.addWidget(mapping) self.widgets.append(mapping) # add horizonal line line = QFrame(self) line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.perm_mappings.addWidget(line) self.widgets.append(line)
def __init__(self, *args): super().__init__(BrickletAnalogIn, *args) self.ai = self.device # the firmware version of a EEPROM Bricklet can (under common circumstances) # not change during the lifetime of an EEPROM Bricklet plugin. therefore, # it's okay to make final decisions based on it here self.has_range = self.firmware_version >= (2, 0, 1) self.has_averaging = self.firmware_version >= (2, 0, 3) self.cbe_voltage = CallbackEmulator(self.ai.get_voltage, None, self.cb_voltage, self.increase_error_count) self.current_voltage = CurveValueWrapper() # float, V plots = [('Voltage', Qt.red, self.current_voltage, format_voltage)] self.plot_widget = PlotWidget('Voltage [V]', plots, y_resolution=0.001) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) if self.has_range: self.combo_range = QComboBox() self.combo_range.addItem('Automatic', BrickletAnalogIn.RANGE_AUTOMATIC) if self.has_averaging: self.combo_range.addItem('0 - 3.30 V', BrickletAnalogIn.RANGE_UP_TO_3V) self.combo_range.addItem('0 - 6.05 V', BrickletAnalogIn.RANGE_UP_TO_6V) self.combo_range.addItem('0 - 10.32 V', BrickletAnalogIn.RANGE_UP_TO_10V) self.combo_range.addItem('0 - 36.30 V', BrickletAnalogIn.RANGE_UP_TO_36V) self.combo_range.addItem('0 - 45.00 V', BrickletAnalogIn.RANGE_UP_TO_45V) self.combo_range.currentIndexChanged.connect(self.range_changed) hlayout = QHBoxLayout() hlayout.addWidget(QLabel('Range:')) hlayout.addWidget(self.combo_range) hlayout.addStretch() if self.has_averaging: self.spin_average = QSpinBox() self.spin_average.setMinimum(0) self.spin_average.setMaximum(255) self.spin_average.setSingleStep(1) self.spin_average.setValue(50) self.spin_average.editingFinished.connect(self.spin_average_finished) hlayout.addWidget(QLabel('Average Length:')) hlayout.addWidget(self.spin_average) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout.addWidget(line) layout.addLayout(hlayout)
def __init__(self, *args): super().__init__(BrickletIndustrialDualAnalogIn, *args) self.analog_in = self.device # the firmware version of a EEPROM Bricklet can (under common circumstances) # not change during the lifetime of an EEPROM Bricklet plugin. therefore, # it's okay to make final decisions based on it here self.has_fixed_calibration = self.firmware_version >= (2, 0, 1) self.cbe_voltage0 = CallbackEmulator(self.analog_in.get_voltage, 0, self.cb_voltage, self.increase_error_count, pass_arguments_to_result_callback=True) self.cbe_voltage1 = CallbackEmulator(self.analog_in.get_voltage, 1, self.cb_voltage, self.increase_error_count, pass_arguments_to_result_callback=True) self.calibration = None self.sample_rate_label = QLabel('Sample Rate:') self.sample_rate_combo = QComboBox() self.sample_rate_combo.addItem('976 Hz') self.sample_rate_combo.addItem('488 Hz') self.sample_rate_combo.addItem('244 Hz') self.sample_rate_combo.addItem('122 Hz') self.sample_rate_combo.addItem('61 Hz') self.sample_rate_combo.addItem('4 Hz') self.sample_rate_combo.addItem('2 Hz') self.sample_rate_combo.addItem('1 Hz') self.current_voltage = [CurveValueWrapper(), CurveValueWrapper()] # float, V self.calibration_button = QPushButton('Calibration...') self.sample_rate_combo.currentIndexChanged.connect(self.sample_rate_combo_index_changed) self.calibration_button.clicked.connect(self.calibration_button_clicked) plots = [('Channel 0', Qt.red, self.current_voltage[0], format_voltage), ('Channel 1', Qt.blue, self.current_voltage[1], format_voltage)] self.plot_widget = PlotWidget('Voltage [V]', plots, y_resolution=0.001) hlayout = QHBoxLayout() hlayout.addWidget(self.sample_rate_label) hlayout.addWidget(self.sample_rate_combo) hlayout.addStretch() hlayout.addWidget(self.calibration_button) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
def __init__(self, *args): super().__init__(BrickletLoadCell, *args) self.lc = self.device self.cbe_weight = CallbackEmulator(self.lc.get_weight, None, self.cb_weight, self.increase_error_count) self.gain = 0 # 128x self.current_weight = CurveValueWrapper() # int, g self.calibration = None plots = [('Weight', Qt.red, self.current_weight, format_weight)] self.plot_widget = PlotWidget('Weight [g]', plots, y_resolution=1.0) self.button_calibration = QPushButton("Calibration...") self.button_calibration.clicked.connect(self.button_calibration_clicked) self.button_tare = QPushButton("Tare") self.button_tare.clicked.connect(self.button_tare_clicked) self.enable_led = QCheckBox("Enable LED") self.enable_led.stateChanged.connect(self.enable_led_changed) self.spin_average = QSpinBox() self.spin_average.setMinimum(0) self.spin_average.setMaximum(40) self.spin_average.setSingleStep(1) self.spin_average.setValue(5) self.spin_average.editingFinished.connect(self.spin_average_finished) self.label_average = QLabel('Moving Average Length:') self.rate_label = QLabel('Rate:') self.rate_combo = QComboBox() self.rate_combo.addItem("10 Hz") self.rate_combo.addItem("80 Hz") self.rate_combo.currentIndexChanged.connect(self.new_config) hlayout = QHBoxLayout() hlayout.addWidget(self.label_average) hlayout.addWidget(self.spin_average) hlayout.addWidget(self.rate_label) hlayout.addWidget(self.rate_combo) hlayout.addStretch() hlayout.addWidget(self.button_calibration) hlayout.addWidget(self.button_tare) hlayout.addWidget(self.enable_led) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
def __init__(self, *args): super().__init__(BrickletUVLightV2, *args) self.uv_light = self.device self.cbe_uva = CallbackEmulator(self.uv_light.get_uva, None, self.cb_uva, self.increase_error_count) self.cbe_uvb = CallbackEmulator(self.uv_light.get_uvb, None, self.cb_uvb, self.increase_error_count) self.cbe_uvi = CallbackEmulator(self.uv_light.get_uvi, None, self.cb_uvi, self.increase_error_count) self.index_label = IndexLabel(' UVI: ? ') self.index_label.setText('0.0') self.current_uva = CurveValueWrapper() self.current_uvb = CurveValueWrapper() plots = [('UVA', Qt.red, self.current_uva, '{} mW/m²'.format), ('UVB', Qt.darkGreen, self.current_uvb, '{} mW/m²'.format)] self.plot_widget = PlotWidget('UV [mW/m²]', plots, extra_key_widgets=[self.index_label], y_resolution=0.1) self.time_label = QLabel('Integration Time:') self.time_combo = QComboBox() self.time_combo.addItem("50 ms", BrickletUVLightV2.INTEGRATION_TIME_50MS) self.time_combo.addItem("100 ms", BrickletUVLightV2.INTEGRATION_TIME_100MS) self.time_combo.addItem("200 ms", BrickletUVLightV2.INTEGRATION_TIME_200MS) self.time_combo.addItem("400 ms", BrickletUVLightV2.INTEGRATION_TIME_400MS) self.time_combo.addItem("800 ms", BrickletUVLightV2.INTEGRATION_TIME_800MS) self.time_combo.currentIndexChanged.connect(self.new_config) self.saturation_label = QLabel('Sensor is saturated, choose a shorter integration time!') self.saturation_label.setStyleSheet('QLabel { color : red }') self.saturation_label.hide() hlayout = QHBoxLayout() hlayout.addWidget(self.time_label) hlayout.addWidget(self.time_combo) hlayout.addStretch() hlayout.addWidget(self.saturation_label) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
def __init__(self, *args): super().__init__(BrickletPTC, *args) self.ptc = self.device self.str_connected = 'Sensor is <font color="green">connected</font>' self.str_not_connected = 'Sensor is <font color="red">not connected</font>' self.cbe_temperature = CallbackEmulator(self.ptc.get_temperature, None, self.cb_temperature, self.increase_error_count) self.wire_label = QLabel('Wire Type:') self.wire_combo = QComboBox() self.wire_combo.addItem('2-Wire') self.wire_combo.addItem('3-Wire') self.wire_combo.addItem('4-Wire') self.noise_label = QLabel('Noise Rejection Filter:') self.noise_combo = QComboBox() self.noise_combo.addItem('50 Hz') self.noise_combo.addItem('60 Hz') self.connected_label = QLabel(self.str_connected) self.current_temperature = CurveValueWrapper() # float, °C self.wire_combo.currentIndexChanged.connect(self.wire_combo_index_changed) self.noise_combo.currentIndexChanged.connect(self.noise_combo_index_changed) plots = [('Temperature', Qt.red, self.current_temperature, '{} °C'.format)] self.plot_widget = PlotWidget('Temperature [°C]', plots, extra_key_widgets=[self.connected_label], y_resolution=0.01) hlayout = QHBoxLayout() hlayout.addWidget(self.wire_label) hlayout.addWidget(self.wire_combo) hlayout.addStretch() hlayout.addWidget(self.noise_label) hlayout.addWidget(self.noise_combo) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout) self.connected_timer = QTimer(self) self.connected_timer.timeout.connect(self.update_connected) self.connected_timer.setInterval(1000)
def __init__(self, parent=None): super().__init__(parent) self.filepath = '' self.layouts = {} self.setWindowModality(Qt.ApplicationModal) self.setWindowTitle('Layout selection') self.setMaximumSize(675, 300) self.setMinimumSize(675, 300) self.resize(675, 300) self.vLayout = QVBoxLayout(self) self.vLayout.setContentsMargins(5, 5, 5, 5) self.hLayout = QHBoxLayout(self) self.vLayout.addLayout(self.hLayout) self.layoutBox = QComboBox(self) self.hLayout.addWidget(self.layoutBox) self.layButton = QPushButton(self) self.layButton.setText('Select layout') self.hLayout.addWidget(self.layButton) self.fileButton = QPushButton(self) self.fileButton.setText('Open file') self.hLayout.addWidget(self.fileButton) self.hLayout.setStretch(0, 3) self.hLayout.setStretch(1, 2) self.hLayout.setStretch(2, 1) line = QFrame(self) line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.vLayout.addWidget(line) self.description = QTextBrowser(self) self.vLayout.addWidget(self.description) for layout_class in layouts.get_layouts(): self.layoutBox.addItem(layout_class.NAME) self.layouts[layout_class.NAME] = (layout_class, layout_class.DESCRIPTION) if self.layoutBox.count() == 0: raise Exception('No layout installed!') self.show_description(self.layoutBox.currentText()) self.layoutBox.currentTextChanged.connect(self.show_description) self.layButton.clicked.connect(self.accept) self.fileButton.clicked.connect(self.open_file)
def __drawSplitterHandle(self, index): splitterHandle = self.splitter.handle(index) splitterLayout = QVBoxLayout(splitterHandle) splitterLayout.setSpacing(0) splitterLayout.setContentsMargins(0, 0, 0, 0) line = QFrame(splitterHandle) line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) splitterLayout.addWidget(line) splitterHandle.setLayout(splitterLayout)
def __init__(self, *args): super().__init__(BrickletHallEffect, *args) self.hf = self.device self.cbe_edge_count = CallbackEmulator(self.get_edge_count, False, self.cb_edge_count, self.increase_error_count, expand_result_tuple_for_callback=True) self.current_value = CurveValueWrapper() self.label_count = CountLabel('Count') plots = [('Value', Qt.red, self.current_value, str)] self.plot_widget = PlotWidget('Value', plots, extra_key_widgets=[self.label_count], update_interval=0.05) self.plot_widget.set_fixed_y_scale(0, 1, 1, 1) self.combo_edge_type = QComboBox() self.combo_edge_type.addItem('Rising') self.combo_edge_type.addItem('Falling') self.combo_edge_type.addItem('Both') self.combo_edge_type.currentIndexChanged.connect(self.edge_changed) self.spin_debounce = QSpinBox() self.spin_debounce.setMinimum(0) self.spin_debounce.setMaximum(255) self.spin_debounce.setValue(100) self.spin_debounce.editingFinished.connect(self.debounce_changed) self.button_reset = QPushButton('Reset Count') self.button_reset.clicked.connect(self.reset_count) hlayout = QHBoxLayout() hlayout.addWidget(QLabel('Edge Type:')) hlayout.addWidget(self.combo_edge_type) hlayout.addStretch() hlayout.addWidget(QLabel('Debounce Period [ms]:')) hlayout.addWidget(self.spin_debounce) hlayout.addStretch() hlayout.addWidget(self.button_reset) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
def __init__(self, *args): super().__init__(BrickletMotorizedLinearPoti, *args) self.mp = self.device self.cbe_position = CallbackEmulator(self.mp.get_position, None, self.cb_position, self.increase_error_count) self.current_position = CurveValueWrapper() self.slider = QSlider(Qt.Horizontal) self.slider.setRange(0, 100) self.slider.setMinimumWidth(200) self.slider.setEnabled(False) plots = [('Potentiometer Position', Qt.red, self.current_position, str)] self.plot_widget = PlotWidget('Position', plots, extra_key_widgets=[self.slider], update_interval=0.025, y_resolution=1.0) self.motor_slider = QSlider(Qt.Horizontal) self.motor_slider.setRange(0, 100) self.motor_slider.valueChanged.connect(self.motor_slider_value_changed) self.motor_hold_position = QCheckBox("Hold Position") self.motor_drive_mode = QComboBox() self.motor_drive_mode.addItem('Fast') self.motor_drive_mode.addItem('Smooth') def get_motor_slider_value(): return self.motor_slider.value() self.motor_hold_position.stateChanged.connect(lambda x: self.motor_slider_value_changed(get_motor_slider_value())) self.motor_drive_mode.currentIndexChanged.connect(lambda x: self.motor_slider_value_changed(get_motor_slider_value())) self.motor_position_label = MotorPositionLabel('Motor Target Position:') hlayout = QHBoxLayout() hlayout.addWidget(self.motor_position_label) hlayout.addWidget(self.motor_slider) hlayout.addWidget(self.motor_drive_mode) hlayout.addWidget(self.motor_hold_position) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
def __init__(self, *args): super().__init__(BrickletDistanceIRV2, *args) self.dist = self.device self.cbe_distance = CallbackEmulator(self.dist.get_distance, None, self.cb_distance, self.increase_error_count) self.cbe_analog_value = CallbackEmulator(self.dist.get_analog_value, None, self.cb_analog_value, self.increase_error_count) self.analog_label = AnalogLabel('Analog Value:') hlayout = QHBoxLayout() self.average_label = QLabel('Moving Average Length:') self.average_spin = QSpinBox() self.average_spin.setMinimum(1) self.average_spin.setMaximum(1000) self.average_spin.setSingleStep(1) self.average_spin.setValue(25) self.average_spin.editingFinished.connect(self.average_spin_finished) self.sensor_label = QLabel('Sensor Type:') self.sensor_combo = QComboBox() self.sensor_combo.addItem('2Y0A41 (4-30cm)') self.sensor_combo.addItem('2Y0A21 (10-80cm)') self.sensor_combo.addItem('2Y0A02 (20-150cm)') self.sensor_combo.currentIndexChanged.connect(self.sensor_combo_changed) hlayout.addWidget(self.average_label) hlayout.addWidget(self.average_spin) hlayout.addStretch() hlayout.addWidget(self.sensor_label) hlayout.addWidget(self.sensor_combo) self.current_distance = CurveValueWrapper() # float, cm plots = [('Distance', Qt.red, self.current_distance, '{} cm'.format)] self.plot_widget = PlotWidget('Distance [cm]', plots, extra_key_widgets=[self.analog_label], y_resolution=0.1) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
def __init__(self, parent=None): super().__init__(parent) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) line = QFrame(self) line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout.addWidget(line) self.text_edit = QTextEdit() self.text_edit.setFixedHeight(100) self.text_edit.setFocusPolicy(Qt.NoFocus) self.text_edit.setReadOnly(True) layout.addWidget(self.text_edit) self.setLayout(layout)
def __init__(self, *args): super().__init__(BrickletAnalogInV3, *args) self.ai = self.device self.cbe_voltage = CallbackEmulator(self.ai.get_voltage, None, self.cb_voltage, self.increase_error_count) self.current_voltage = CurveValueWrapper() # float, V plots = [('Voltage', Qt.red, self.current_voltage, format_voltage)] self.plot_widget = PlotWidget('Voltage [V]', plots, y_resolution=0.001) self.oversampling_combo = QComboBox() self.oversampling_combo.addItem('32x (0.56ms)') self.oversampling_combo.addItem('64x (1.12ms)') self.oversampling_combo.addItem('128x (2.24ms)') self.oversampling_combo.addItem('256x (4.48ms)') self.oversampling_combo.addItem('512x (8.96ms)') self.oversampling_combo.addItem('1024x (17.92ms)') self.oversampling_combo.addItem('2048x (35.84ms)') self.oversampling_combo.addItem('4096x (71.68ms)') self.oversampling_combo.addItem('8192x (143.36ms)') self.oversampling_combo.addItem('16384x (286.72ms)') self.oversampling_combo.currentIndexChanged.connect(self.oversampling_combo_index_changed) self.calibration = None self.calibration_button = QPushButton('Calibration...') self.calibration_button.clicked.connect(self.calibration_button_clicked) layout_h1 = QHBoxLayout() layout_h1.addWidget(QLabel('Oversampling:')) layout_h1.addWidget(self.oversampling_combo) layout_h1.addStretch() layout_h1.addWidget(self.calibration_button) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(layout_h1)
def initCtrPane(self): # main control set up mainCtr = QFrame(self.ctrPane) mainCtr.setFrameShape(QFrame.StyledPanel) mainCtr.setFrameShadow(QFrame.Sunken) # buttons and controls backSubButton = QPushButton('Background Subtraction', mainCtr) backSubButton.clicked.connect(self.backSub) plotButton = QPushButton('Plot', mainCtr) plotButton.clicked.connect(self.updatePlot1) newTabButton = QPushButton('New tab', mainCtr) newTabButton.clicked.connect(self.addTab) self.plotPeak = QCheckBox('Plot fitted peak', mainCtr) holdPlot = QCheckBox('Hold plot', mainCtr) holdPlot.stateChanged.connect(self.canvas.toggleHold) # layout mainLayout = QGridLayout(mainCtr) mainLayout.addWidget(backSubButton, 0, 0) mainLayout.addWidget(plotButton, 0, 1) mainLayout.addWidget(newTabButton, 1, 0) mainLayout.addWidget(self.plotPeak, 2, 0) mainLayout.addWidget(holdPlot, 2, 1) mainCtr.setLayout(mainLayout) self.ctrPane.addTab(mainCtr, 'Main Control') # NMF control set up NMFCtr = QFrame(self.ctrPane) NMFCtr.setFrameShape(QFrame.StyledPanel) NMFCtr.setFrameShadow(QFrame.Sunken) # input & buttons self.alphaBox = MyDoubleBox(NMFCtr) self.l1RatioBox = MyDoubleBox(NMFCtr) self.loadSettings() NMFButton = QPushButton('NMF', NMFCtr) NMFButton.clicked.connect(self.NMF) # layout NMFLayout = QGridLayout(NMFCtr) NMFLayout.addWidget(QLabel('α'), 0, 0) NMFLayout.addWidget(QLabel('l1 ratio'), 1, 0) NMFLayout.addWidget(self.alphaBox, 0, 1) NMFLayout.addWidget(self.l1RatioBox, 1, 1) NMFLayout.addWidget(NMFButton, 2, 0, 1, 2) NMFCtr.setLayout(NMFLayout) self.ctrPane.addTab(NMFCtr, 'NMF Control')
def __init__(self, *args): super().__init__(BrickletACCurrent, *args) self.acc = self.device self.cbe_current = CallbackEmulator(self.acc.get_current, None, self.cb_current, self.increase_error_count) self.current_current = CurveValueWrapper() # float, A plots = [('Current', Qt.red, self.current_current, format_current)] self.plot_widget = PlotWidget('Current [A]', plots, y_resolution=0.001) self.label_average = QLabel('Moving Average Length:') self.spin_average = QSpinBox() self.spin_average.setMinimum(1) self.spin_average.setMaximum(50) self.spin_average.setSingleStep(1) self.spin_average.setValue(50) self.spin_average.editingFinished.connect(self.spin_average_finished) self.label_range = QLabel('Current Range:') self.combo_range = QComboBox() self.combo_range.addItem("0") # TODO: Adjust ranges self.combo_range.addItem("1") self.combo_range.currentIndexChanged.connect(self.new_config) hlayout = QHBoxLayout() hlayout.addWidget(self.label_average) hlayout.addWidget(self.spin_average) hlayout.addStretch() hlayout.addWidget(self.label_range) hlayout.addWidget(self.combo_range) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
def __init__(self, *args): super().__init__(BrickletPressure, *args) self.p = self.device self.cbe_pressure = CallbackEmulator(self.p.get_pressure, None, self.cb_pressure, self.increase_error_count) self.current_pressure = CurveValueWrapper() # float, kPa plots = [('Pressure', Qt.red, self.current_pressure, '{:.3f} kPa'.format)] self.plot_widget = PlotWidget('Pressure [kPa]', plots, y_resolution=0.001) self.combo_sensor = QComboBox() self.combo_sensor.addItem('MPX5500') self.combo_sensor.addItem('MPXV5004') self.combo_sensor.addItem('MPX4115A') self.combo_sensor.currentIndexChanged.connect(self.combo_sensor_changed) self.spin_average = QSpinBox() self.spin_average.setMinimum(1) self.spin_average.setMaximum(50) self.spin_average.setSingleStep(1) self.spin_average.setValue(50) self.spin_average.editingFinished.connect(self.spin_average_finished) hlayout = QHBoxLayout() hlayout.addWidget(QLabel('Sensor Type:')) hlayout.addWidget(self.combo_sensor) hlayout.addStretch() hlayout.addWidget(QLabel('Moving Average Length:')) hlayout.addWidget(self.spin_average) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
def __init__(self, *args): super().__init__(BrickletTemperatureIRV2, *args) self.tir = self.device self.cbe_ambient_temperature = CallbackEmulator(self.tir.get_ambient_temperature, None, self.cb_ambient_temperature, self.increase_error_count) self.cbe_object_temperature = CallbackEmulator(self.tir.get_object_temperature, None, self.cb_object_temperature, self.increase_error_count) self.current_ambient = CurveValueWrapper() # float, °C self.current_object = CurveValueWrapper() # float, °C plots = [('Ambient', Qt.blue, self.current_ambient, '{} °C'.format), ('Object', Qt.red, self.current_object, '{} °C'.format)] self.plot_widget = PlotWidget('Temperature [°C]', plots, y_resolution=0.1) self.spin_emissivity = QSpinBox() self.spin_emissivity.setMinimum(6553) self.spin_emissivity.setMaximum(65535) self.spin_emissivity.setValue(65535) self.spin_emissivity.editingFinished.connect(self.spin_emissivity_finished) hlayout = QHBoxLayout() hlayout.addWidget(QLabel('Emissivity:')) hlayout.addWidget(self.spin_emissivity) hlayout.addStretch() line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
def initUI(self, tweet): layout = QGridLayout() self.setLayout(layout) self.lay = layout layout.setColumnStretch(10, 100) self.add_pic() self.add_time() self.add_text() self.add_username() self.add_button() line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout.addWidget(line, 4, 0, 1, -1) self.setLayout(layout) layout.setSpacing(5) layout.setContentsMargins(0, 0, 0, 0)
def __init__(self, *args): super().__init__(BrickletDistanceUS, *args) self.dist = self.device self.cbe_distance = CallbackEmulator(self.dist.get_distance_value, None, self.cb_distance, self.increase_error_count) self.current_distance = CurveValueWrapper() plots = [('Distance Value', Qt.red, self.current_distance, str)] self.plot_widget = PlotWidget('Distance Value', plots, y_resolution=1.0) self.spin_average = QSpinBox() self.spin_average.setMinimum(0) self.spin_average.setMaximum(100) self.spin_average.setSingleStep(1) self.spin_average.setValue(20) self.spin_average.editingFinished.connect(self.spin_average_finished) hlayout = QHBoxLayout() hlayout.addWidget(QLabel('Moving Average Length:')) hlayout.addWidget(self.spin_average) hlayout.addStretch() line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
def __init__(self, *args): super().__init__(BrickletOzone, *args) self.ozone = self.device self.cbe_ozone_concentration = CallbackEmulator(self.ozone.get_ozone_concentration, None, self.cb_ozone_concentration, self.increase_error_count) self.current_ozone_concentration = CurveValueWrapper() plots = [('Ozone Concentration', Qt.red, self.current_ozone_concentration, '{} ppb'.format)] self.plot_widget = PlotWidget('Ozone Concentration [ppb]', plots, y_resolution=1.0) self.spin_average = QSpinBox() self.spin_average.setMinimum(1) self.spin_average.setMaximum(50) self.spin_average.setSingleStep(1) self.spin_average.setValue(50) self.spin_average.editingFinished.connect(self.spin_average_finished) hlayout = QHBoxLayout() hlayout.addWidget(QLabel('Moving Average Length:')) hlayout.addWidget(self.spin_average) hlayout.addStretch() line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
class MainWindow(QWidget, Ui_MainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.config = Config() self.setWindowFlag(QtCore.Qt.FramelessWindowHint) self.tabWidget = QTabWidget() self._mainLayout = QVBoxLayout() self._topBar = QHBoxLayout() self.windowCloseButton = QPushButton() self.windowCloseButton.setText("X") self.windowCloseButton.setFixedWidth(25) self.windowCloseButton.setFixedHeight(25) self.windowCloseButton.clicked.connect(lambda: self.close()) self._windowMoveLine = QFrame() self._windowMoveLine.setFrameShadow(QFrame.Plain) self._windowMoveLine.setStyleSheet("background: black;") self._windowMoveLine.setFrameShape(QFrame.HLine) self._windowMoveLine.setMinimumSize(10, 10) self._topBar.addWidget(self._windowMoveLine) self._topBar.addWidget((self.windowCloseButton)) self._mainLayout.addLayout(self._topBar) self._mainLayout.addWidget(self.tabWidget) self.setLayout(self._mainLayout) self._windowMoveLine.mousePressEvent = self.windowBarMove self._windowMoveLine.mouseMoveEvent = self.windowBarMove try: self.config = pickle.load(open('config.pkl', 'rb')) except: print("error opening Config File") self.isRoboKittyConnected = False self.areMotorsEnabled = False self.RearRightShoulder = None # type:AX12A self.RearRightFemur = None # type:AX12A self.RearRightLeg = None # type:AX12A self.RearLeftShoulder = None # type:AX12A self.RearLeftFemur = None # type:AX12A self.RearLeftLeg = None # type:AX12A self.FrontLeftShoulder = None # type:AX12A self.FrontLeftFemur = None # type:AX12A self.FrontLeftLeg = None # type:AX12A self.FrontRightShoulder = None # type:AX12A self.FrontRightFemur = None # type:AX12A self.FrontRightLeg = None # type:AX12A self.ax12aInstances = [] AX12A.debugEnabled = False sizeGrip = QSizeGrip(self) sizeGrip.setVisible(True) self._mainLayout.addWidget( sizeGrip, 0, QtCore.Qt.AlignBottom | QtCore.Qt.AlignRight) self.setupUi(self.tabWidget) self.tabWidget.setCurrentIndex(1) self.init() def keyPressEvent(self, a0) -> None: pass def windowBarMove(self, event: QMouseEvent): if event.type() == QtCore.QEvent.MouseButtonPress: self.oldPos = event.globalPos() elif event.type() == QtCore.QEvent.MouseMove: delta = QtCore.QPoint(event.globalPos() - self.oldPos) self.move(self.x() + delta.x(), self.y() + delta.y()) self.oldPos = event.globalPos() # def resizeEvent(self, a0: QResizeEvent) -> None: # QTabWidget.resizeEvent(self,a0) # print(a0.size()) def closeEvent(self, a0: QCloseEvent) -> None: pickle.dump(self.config, open('config.pkl', 'wb')) print('Closed') def enableMotors(self, value): if self.isRoboKittyConnected: if value: self.areMotorsEnabled = True AX12A.setEnableTorqueGroup(self.ax12aInstances, 1) else: self.areMotorsEnabled = False AX12A.setEnableTorqueGroup(self.ax12aInstances, 0) def tabChanged(self, index): if index == 0: pass # self.setFixedSize(890,300) elif index == 1: self.centerServoTab.onTabActivate() # self.setFixedSize(890,400) elif index == 2: pass # self.setFixedSize(802,324) elif index == 4: # self.setFixedSize(1558,619) self.motionRecorderTab.motors = [ ["Front Left Shoulder", self.FrontLeftShoulder], ["Front Left Femur", self.FrontLeftFemur], ["Front Left Leg", self.FrontLeftLeg], ["Front Right Shoulder", self.FrontRightShoulder], ["Front Right Femur", self.FrontRightFemur], ["Front Right Leg", self.FrontRightLeg], ["Rear Left Shoulder", self.RearLeftShoulder], ["Rear Left Femur", self.RearLeftFemur], ["Rear Left Leg", self.RearLeftLeg], ["Rear Right Shoulder", self.RearRightShoulder], ["Rear Right Femur", self.RearRightFemur], ["Rear Right Leg", self.RearRightLeg], ] self.motionRecorderTab.motionDataModel.setHeaderLabels( [x[0] for x in self.motionRecorderTab.motors] + ["Delay (milliseconds)", "Torque"]) self.motionRecorderTab.initValues() elif index == 3: pass def init(self): self.tabWidget.currentChanged.connect(self.tabChanged) self.calibrateServoTab = CalibrateServoTab(self) self.setupTab = SetupTab(self) self.manualControlTab = ManualControlTab(self) self.motionRecorderTab = MotionRecorderTab(self) self.centerServoTab = CenterServoTab(self)
class FolderDialog(QDialog): def __init__(self, parent=None): super(QDialog, self).__init__(parent) self.parent = parent self.resize(400, 300) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setSpacing(5) self.verticalLayout.setContentsMargins(5, 5, 5, 5) self.labelName = QLabel(self) self.verticalLayout.addWidget(self.labelName) self.lineEditFolder = QLineEdit(self) self.verticalLayout.addWidget(self.lineEditFolder) self.labelWarning = QLabel(self) self.labelWarning.hide() self.verticalLayout.addWidget(self.labelWarning) self.labelFolder = QLabel(self) self.verticalLayout.addWidget(self.labelFolder) self.treeWidget = QTreeWidget(self) self.treeWidget.setAlternatingRowColors(True) self.treeWidget.setIconSize(QSize(12, 12)) self.treeWidget.setAnimated(True) self.treeWidget.header().setVisible(False) self.verticalLayout.addWidget(self.treeWidget) self.line = QFrame(self) self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(self.line) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Save) self.buttonBox.button(QDialogButtonBox.Cancel).setText(self.tr("Cancel")) self.buttonBox.button(QDialogButtonBox.Save).setText(self.tr("Save")) self.verticalLayout.addWidget(self.buttonBox) self.buttonBox.button(QDialogButtonBox.Save).clicked.connect(self.folderAdd) self.buttonBox.button(QDialogButtonBox.Cancel).clicked.connect(self.reject) self.lineEditFolder.returnPressed.connect(self.buttonBox.button(QDialogButtonBox.Save).toggle) self.lineEditFolder.textChanged.connect(self.labelWarning.hide) self.setWindowTitle(self.tr("Add Folder")) self.labelName.setText(self.tr("Name:")) self.labelFolder.setText(self.tr("Insert:")) self.treeWidget.headerItem().setText(0, self.tr("Folder")) self.treeWidget.setIconSize(QSize(18, 18)) self.categorySorting(treeitem=self.treeWidget) def categorySorting(self, id=0, treeitem=None): db = ReaderDb() db.execute("select * from folders where type='folder' and parent=?",(id,)) folders = db.cursor.fetchall() for folder in folders: item = QTreeWidgetItem(treeitem) item.setIcon(0, QIcon(":/images/icons/folder_grey.png")) item.id = folder["id"] item.category_name = folder[1] item.setText(0, item.category_name) item.subcategory = folder["parent"] self.categorySorting(folder["id"], item) def folderAdd(self): text = self.lineEditFolder.text() db = ReaderDb() if len(text): control = db.execute("select * from folders where title=?", (text,)) if not control.fetchone(): if self.treeWidget.currentItem() == None or not len(self.treeWidget.selectedItems()): db.execute("insert into folders (title, type) values (?, 'folder')", (text,)) db.commit() db.close() else: db.execute("insert into folders (title, parent, type) values (?, ?, 'folder')", (text, self.treeWidget.currentItem().id)) db.commit() db.close() self.parent.syncSignal.emit() self.parent.categorySync() self.close() else: self.labelWarning.setText(self.tr("<span style='color:red; font-size:15px; font-weight:bold;'>Same category name cannot add!</span>")) self.labelWarning.show() else: self.labelWarning.setText(self.tr("<span style='color:red; font-size:15px; font-weight:bold; align:'center';'>You didn't write folder's name!</span>")) self.labelWarning.show()
class AddLinkWindow_Ui(QWidget): def __init__(self, persepolis_setting): super().__init__() self.persepolis_setting = persepolis_setting # get icons name icons = ':/' + \ str(self.persepolis_setting.value('settings/icons')) + '/' self.setMinimumSize(QtCore.QSize(520, 265)) self.setWindowIcon(QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg'))) window_verticalLayout = QVBoxLayout() window_verticalLayout.setContentsMargins(-1, 10, -1, -1) self.link_frame = QFrame(self) self.link_frame.setFrameShape(QFrame.StyledPanel) self.link_frame.setFrameShadow(QFrame.Raised) horizontalLayout_2 = QHBoxLayout(self.link_frame) link_verticalLayout = QVBoxLayout() # link -> link_horizontalLayout = QHBoxLayout() self.link_label = QLabel(self.link_frame) link_horizontalLayout.addWidget(self.link_label) self.link_lineEdit = QLineEdit(self.link_frame) link_horizontalLayout.addWidget(self.link_lineEdit) link_verticalLayout.addLayout(link_horizontalLayout) horizontalLayout_2.addLayout(link_verticalLayout) window_verticalLayout.addWidget(self.link_frame) # add change_name field -> change_name_horizontalLayout = QHBoxLayout() self.change_name_checkBox = QCheckBox(self.link_frame) change_name_horizontalLayout.addWidget(self.change_name_checkBox) self.change_name_lineEdit = QLineEdit(self.link_frame) change_name_horizontalLayout.addWidget(self.change_name_lineEdit) link_verticalLayout.addLayout(change_name_horizontalLayout) # add_category -> queue_horizontalLayout = QHBoxLayout() self.queue_frame = QFrame(self) self.queue_frame.setFrameShape(QFrame.StyledPanel) self.queue_frame.setFrameShadow(QFrame.Raised) add_queue_horizontalLayout = QHBoxLayout(self.queue_frame) self.add_queue_label = QLabel(self.queue_frame) add_queue_horizontalLayout.addWidget(self.add_queue_label) self.add_queue_comboBox = QComboBox(self.queue_frame) add_queue_horizontalLayout.addWidget(self.add_queue_comboBox) queue_horizontalLayout.addWidget(self.queue_frame) queue_horizontalLayout.addStretch(1) self.size_label = QLabel(self) queue_horizontalLayout.addWidget(self.size_label) window_verticalLayout.addLayout(queue_horizontalLayout) # options_pushButton options_horizontalLayout = QHBoxLayout() self.options_pushButton = QPushButton(self) self.options_pushButton.setFlat(True) options_horizontalLayout.addWidget(self.options_pushButton) options_horizontalLayout.addStretch(1) window_verticalLayout.addLayout(options_horizontalLayout) # proxy -> proxy_verticalLayout = QVBoxLayout() proxy_horizontalLayout = QHBoxLayout() self.proxy_checkBox = QCheckBox(self) self.detect_proxy_pushButton = QPushButton(self) self.detect_proxy_label = QLabel(self) proxy_horizontalLayout.addWidget(self.proxy_checkBox) proxy_horizontalLayout.addWidget(self.detect_proxy_label) proxy_horizontalLayout.addWidget(self.detect_proxy_pushButton) proxy_verticalLayout.addLayout(proxy_horizontalLayout) self.proxy_frame = QFrame(self) self.proxy_frame.setFrameShape(QFrame.StyledPanel) self.proxy_frame.setFrameShadow(QFrame.Raised) gridLayout = QGridLayout(self.proxy_frame) self.ip_lineEdit = QLineEdit(self.proxy_frame) self.ip_lineEdit.setInputMethodHints(QtCore.Qt.ImhNone) gridLayout.addWidget(self.ip_lineEdit, 0, 1, 1, 1) self.proxy_pass_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.proxy_pass_label, 2, 2, 1, 1) self.proxy_pass_lineEdit = QLineEdit(self.proxy_frame) self.proxy_pass_lineEdit.setEchoMode(QLineEdit.Password) gridLayout.addWidget(self.proxy_pass_lineEdit, 2, 3, 1, 1) self.ip_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.ip_label, 0, 0, 1, 1) self.proxy_user_lineEdit = QLineEdit(self.proxy_frame) gridLayout.addWidget(self.proxy_user_lineEdit, 0, 3, 1, 1) self.proxy_user_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.proxy_user_label, 0, 2, 1, 1) self.port_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.port_label, 2, 0, 1, 1) self.port_spinBox = QSpinBox(self.proxy_frame) self.port_spinBox.setMaximum(65535) self.port_spinBox.setSingleStep(1) gridLayout.addWidget(self.port_spinBox, 2, 1, 1, 1) proxy_verticalLayout.addWidget(self.proxy_frame) window_verticalLayout.addLayout(proxy_verticalLayout) # download UserName & Password -> download_horizontalLayout = QHBoxLayout() download_horizontalLayout.setContentsMargins(-1, 10, -1, -1) download_verticalLayout = QVBoxLayout() self.download_checkBox = QCheckBox(self) download_verticalLayout.addWidget(self.download_checkBox) self.download_frame = QFrame(self) self.download_frame.setFrameShape(QFrame.StyledPanel) self.download_frame.setFrameShadow(QFrame.Raised) gridLayout_2 = QGridLayout(self.download_frame) self.download_user_lineEdit = QLineEdit(self.download_frame) gridLayout_2.addWidget(self.download_user_lineEdit, 0, 1, 1, 1) self.download_user_label = QLabel(self.download_frame) gridLayout_2.addWidget(self.download_user_label, 0, 0, 1, 1) self.download_pass_label = QLabel(self.download_frame) gridLayout_2.addWidget(self.download_pass_label, 1, 0, 1, 1) self.download_pass_lineEdit = QLineEdit(self.download_frame) self.download_pass_lineEdit.setEchoMode(QLineEdit.Password) gridLayout_2.addWidget(self.download_pass_lineEdit, 1, 1, 1, 1) download_verticalLayout.addWidget(self.download_frame) download_horizontalLayout.addLayout(download_verticalLayout) # select folder -> self.folder_frame = QFrame(self) self.folder_frame.setFrameShape(QFrame.StyledPanel) self.folder_frame.setFrameShadow(QFrame.Raised) gridLayout_3 = QGridLayout(self.folder_frame) self.download_folder_lineEdit = QLineEdit(self.folder_frame) gridLayout_3.addWidget(self.download_folder_lineEdit, 2, 0, 1, 1) self.folder_pushButton = QPushButton(self.folder_frame) gridLayout_3.addWidget(self.folder_pushButton, 3, 0, 1, 1) self.folder_pushButton.setIcon(QIcon(icons + 'folder')) self.folder_label = QLabel(self.folder_frame) self.folder_label.setAlignment(QtCore.Qt.AlignCenter) gridLayout_3.addWidget(self.folder_label, 1, 0, 1, 1) download_horizontalLayout.addWidget(self.folder_frame) window_verticalLayout.addLayout(download_horizontalLayout) # start time -> time_limit_horizontalLayout = QHBoxLayout() time_limit_horizontalLayout.setContentsMargins(-1, 10, -1, -1) start_verticalLayout = QVBoxLayout() self.start_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.start_checkBox) self.start_frame = QFrame(self) self.start_frame.setFrameShape(QFrame.StyledPanel) self.start_frame.setFrameShadow(QFrame.Raised) horizontalLayout_5 = QHBoxLayout(self.start_frame) self.start_time_qDataTimeEdit = QDateTimeEdit(self.start_frame) self.start_time_qDataTimeEdit.setDisplayFormat('H:mm') horizontalLayout_5.addWidget(self.start_time_qDataTimeEdit) start_verticalLayout.addWidget(self.start_frame) time_limit_horizontalLayout.addLayout(start_verticalLayout) # end time -> end_verticalLayout = QVBoxLayout() self.end_checkBox = QCheckBox(self) end_verticalLayout.addWidget(self.end_checkBox) self.end_frame = QFrame(self) self.end_frame.setFrameShape(QFrame.StyledPanel) self.end_frame.setFrameShadow(QFrame.Raised) horizontalLayout_6 = QHBoxLayout(self.end_frame) self.end_time_qDateTimeEdit = QDateTimeEdit(self.end_frame) self.end_time_qDateTimeEdit.setDisplayFormat('H:mm') horizontalLayout_6.addWidget(self.end_time_qDateTimeEdit) end_verticalLayout.addWidget(self.end_frame) time_limit_horizontalLayout.addLayout(end_verticalLayout) # limit Speed -> limit_verticalLayout = QVBoxLayout() self.limit_checkBox = QCheckBox(self) limit_verticalLayout.addWidget(self.limit_checkBox) self.limit_frame = QFrame(self) self.limit_frame.setFrameShape(QFrame.StyledPanel) self.limit_frame.setFrameShadow(QFrame.Raised) horizontalLayout_4 = QHBoxLayout(self.limit_frame) self.limit_spinBox = QDoubleSpinBox(self.limit_frame) self.limit_spinBox.setMinimum(1) self.limit_spinBox.setMaximum(1023) horizontalLayout_4.addWidget(self.limit_spinBox) self.limit_comboBox = QComboBox(self.limit_frame) self.limit_comboBox.addItem("") self.limit_comboBox.addItem("") horizontalLayout_4.addWidget(self.limit_comboBox) limit_verticalLayout.addWidget(self.limit_frame) time_limit_horizontalLayout.addLayout(limit_verticalLayout) window_verticalLayout.addLayout(time_limit_horizontalLayout) # number of connections -> connections_horizontalLayout = QHBoxLayout() connections_horizontalLayout.setContentsMargins(-1, 10, -1, -1) self.connections_frame = QFrame(self) self.connections_frame.setFrameShape(QFrame.StyledPanel) self.connections_frame.setFrameShadow(QFrame.Raised) horizontalLayout_3 = QHBoxLayout(self.connections_frame) self.connections_label = QLabel(self.connections_frame) horizontalLayout_3.addWidget(self.connections_label) self.connections_spinBox = QSpinBox(self.connections_frame) self.connections_spinBox.setMinimum(1) self.connections_spinBox.setMaximum(16) self.connections_spinBox.setProperty("value", 16) horizontalLayout_3.addWidget(self.connections_spinBox) connections_horizontalLayout.addWidget(self.connections_frame) connections_horizontalLayout.addStretch(1) window_verticalLayout.addLayout(connections_horizontalLayout) # ok cancel download_later buttons -> buttons_horizontalLayout = QHBoxLayout() buttons_horizontalLayout.addStretch(1) self.download_later_pushButton = QPushButton(self) self.download_later_pushButton.setIcon(QIcon(icons + 'stop')) self.cancel_pushButton = QPushButton(self) self.cancel_pushButton.setIcon(QIcon(icons + 'remove')) self.ok_pushButton = QPushButton(self) self.ok_pushButton.setIcon(QIcon(icons + 'ok')) buttons_horizontalLayout.addWidget(self.download_later_pushButton) buttons_horizontalLayout.addWidget(self.cancel_pushButton) buttons_horizontalLayout.addWidget(self.ok_pushButton) window_verticalLayout.addLayout(buttons_horizontalLayout) self.setLayout(window_verticalLayout) # labels -> self.setWindowTitle("Enter Your Link") self.link_label.setText("Download Link : ") self.add_queue_label.setText("Add to category : ") self.change_name_checkBox.setText("Change File Name : ") self.options_pushButton.setText("Show more options") self.detect_proxy_pushButton.setText("Detect system proxy setting") self.proxy_checkBox.setText("Proxy") self.proxy_pass_label.setText("Proxy PassWord : "******"IP : ") self.proxy_user_label.setText("Proxy UserName : "******"Port:") self.download_checkBox.setText("Download UserName and PassWord") self.download_user_label.setText("Download UserName : "******"Download PassWord : "******"Change Download Folder") self.folder_label.setText("Download Folder : ") self.start_checkBox.setText("Start Time") self.end_checkBox.setText("End Time") self.limit_checkBox.setText("Limit Speed") self.limit_comboBox.setItemText(0, "KB/S") self.limit_comboBox.setItemText(1, "MB/S") self.connections_label.setText("Number Of Connections :") self.cancel_pushButton.setText("Cancel") self.ok_pushButton.setText("OK") self.download_later_pushButton.setText("Download later") def changeIcon(self, icons): icons = ':/' + str(icons) + '/' self.folder_pushButton.setIcon(QIcon(icons + 'folder')) self.download_later_pushButton.setIcon(QIcon(icons + 'stop')) self.cancel_pushButton.setIcon(QIcon(icons + 'remove')) self.ok_pushButton.setIcon(QIcon(icons + 'ok'))
class UIColorSpace(object): def __init__(self): self.mainDialog = colorspacedialog.ColorSpaceDialog() self.mainLayout = QVBoxLayout(self.mainDialog) self.formLayout = QFormLayout() self.documentLayout = QVBoxLayout() self.refreshButton = QPushButton(QIcon(':/icons/refresh.svg'), i18n("Refresh")) self.widgetDocuments = QListWidget() self.colorModelComboBox = colormodelcombobox.ColorModelComboBox(self) self.colorDepthComboBox = colordepthcombobox.ColorDepthComboBox(self) self.colorProfileComboBox = colorprofilecombobox.ColorProfileComboBox( self) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.kritaInstance = krita.Krita.instance() self.documentsList = [] self.colorModelsList = [] self.colorDepthsList = [] self.colorProfilesList = [] self.refreshButton.clicked.connect(self.refreshButtonClicked) self.buttonBox.accepted.connect(self.confirmButton) self.buttonBox.rejected.connect(self.mainDialog.close) self.mainDialog.setWindowModality(Qt.NonModal) self.widgetDocuments.setSelectionMode(QAbstractItemView.MultiSelection) self.widgetDocuments.setSizeAdjustPolicy( QAbstractScrollArea.AdjustToContents) def initialize(self): self.loadDocuments() self.loadColorModels() self.loadColorDepths() self.loadColorProfiles() self.documentLayout.addWidget(self.widgetDocuments) self.documentLayout.addWidget(self.refreshButton) self.formLayout.addRow(i18n("Documents:"), self.documentLayout) self.formLayout.addRow(i18n("Color model:"), self.colorModelComboBox) self.formLayout.addRow(i18n("Color depth:"), self.colorDepthComboBox) self.formLayout.addRow(i18n("Color profile:"), self.colorProfileComboBox) self.line = QFrame() self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.mainLayout.addLayout(self.formLayout) self.mainLayout.addWidget(self.line) self.mainLayout.addWidget(self.buttonBox) self.mainDialog.resize(500, 300) self.mainDialog.setWindowTitle(i18n("Color Space")) self.mainDialog.setSizeGripEnabled(True) self.mainDialog.show() self.mainDialog.activateWindow() def loadColorModels(self): self.colorModelsList = sorted(self.kritaInstance.colorModels()) self.colorModelComboBox.addItems(self.colorModelsList) def loadColorDepths(self): self.colorDepthComboBox.clear() colorModel = self.colorModelComboBox.currentText() self.colorDepthsList = sorted( self.kritaInstance.colorDepths(colorModel)) self.colorDepthComboBox.addItems(self.colorDepthsList) def loadColorProfiles(self): self.colorProfileComboBox.clear() colorModel = self.colorModelComboBox.currentText() colorDepth = self.colorDepthComboBox.currentText() self.colorProfilesList = sorted( self.kritaInstance.profiles(colorModel, colorDepth)) self.colorProfileComboBox.addItems(self.colorProfilesList) def loadDocuments(self): self.widgetDocuments.clear() self.documentsList = [ document for document in self.kritaInstance.documents() if document.fileName() ] for document in self.documentsList: self.widgetDocuments.addItem(document.fileName()) def refreshButtonClicked(self): self.loadDocuments() def confirmButton(self): selectedPaths = [ item.text() for item in self.widgetDocuments.selectedItems() ] selectedDocuments = [ document for document in self.documentsList for path in selectedPaths if path == document.fileName() ] self.msgBox = QMessageBox(self.mainDialog) if selectedDocuments: self.convertColorSpace(selectedDocuments) self.msgBox.setText( i18n("The selected documents has been converted.")) else: self.msgBox.setText(i18n("Select at least one document.")) self.msgBox.exec_() def convertColorSpace(self, documents): for document in documents: document.setColorSpace(self.colorModelComboBox.currentText(), self.colorDepthComboBox.currentText(), self.colorProfileComboBox.currentText())
class GuiMain(object): """ Static GUI class See module docstring for explanation. """ def setupUi(self, MainWindow): """ __init__ :param MainWindow: mainwindow object called in guis_event_handler.py """ # Presets self._presets(MainWindow) # Main Frames # *********************************************************** self._main_frame() # *********************************************************** # Left Side # *********************************************************** self._left_side() # *********************************************************** # *********************************************************** # Right Side self._right_side() # *********************************************************** # Postsets self._postsets() def _main_frame(self): """ Main layout and frame. Separation in left and right side. """ self.MainWindow.resize(1200, 900) self.MainWindow.setWindowTitle("NOViZ") self.centralwidget = QWidget(self.MainWindow) self.centralwidget.setObjectName("centralwidget") self.MainWindow.setWindowIcon(QIcon(module_dir + 'gui_imgs/NoviZ4.png')) # menu layout self.verticalLayout_menu = QVBoxLayout(self.centralwidget) self.verticalLayout_menu.setObjectName("verticalLayout_menu") self._add_menus_on_top() # main layout self.horizontalLayout_main = QHBoxLayout() self.horizontalLayout_main.setObjectName("verticalLayout_menu") self.verticalLayout_menu.addLayout(self.horizontalLayout_main) # left frame and left layout self.frame_left = QFrame() self.frame_left.setObjectName("frame_left") self.frame_left.setFrameShape(QFrame.StyledPanel) self.frame_left.setFrameShadow(QFrame.Plain) self.frame_left.setLineWidth(10) self.verticalLayout_left = QVBoxLayout(self.frame_left) self.verticalLayout_left.setObjectName("verticalLayout_left") self.horizontalLayout_main.addWidget(self.frame_left) # right frame and right layout self.frame_right = QFrame() self.frame_right.setObjectName("frame_right") self.frame_right.setFrameShape(QFrame.StyledPanel) self.frame_right.setFrameShadow(QFrame.Plain) self.frame_right.setLineWidth(10) self.verticalLayout_right = QVBoxLayout(self.frame_right) self.verticalLayout_right.setObjectName("verticalLayout_right") self.verticalLayout_right.setSizeConstraint(4) self.horizontalLayout_main.addWidget(self.frame_right) def _add_menus_on_top(self): """ init main menu """ # set up menu bar self.main_menu = QMenuBar() self.main_menu.setObjectName("main_menu") self.verticalLayout_menu.addWidget(self.main_menu) # menu entrys # file menu self.file_menu = self.main_menu.addMenu('File') self.file_menu.setObjectName("file_menu") # save self.menu_file_save = QAction("Save") self.menu_file_save.setShortcut('Ctrl+S') self.menu_file_save.setStatusTip('Save current image') self.menu_file_save.setObjectName("menu_file_save") self.file_menu.addAction(self.menu_file_save) # exit self.menu_file_exit = QAction("Exit") self.menu_file_exit.setShortcut('Ctrl+Q') self.menu_file_exit.setStatusTip('Exit application') self.menu_file_exit.setObjectName("menu_file_exit") self.file_menu.addAction(self.menu_file_exit) # view menu self.view_menu = self.main_menu.addMenu('View') self.view_menu.setObjectName("view_menu") # tracing self.menu_view_trace = QAction("Focus tracing") self.menu_view_trace.setShortcut('Ctrl+Alt+T') self.menu_view_trace.setStatusTip("Trace current point") self.menu_view_trace.setObjectName("menu_view_trace") self.view_menu.addAction(self.menu_view_trace) # dark theme self.menu_view_theme = QAction("Dark theme") self.menu_view_theme.setShortcut('Ctrl+Alt+D') self.menu_view_theme.setStatusTip("Activate dark theme") self.menu_view_theme.setObjectName("menu_view_theme") self.view_menu.addAction(self.menu_view_theme) # settings menu self.settings_menu = self.main_menu.addMenu('Settings') self.settings_menu.setObjectName("settings_menu") # figure setup self.menu_settings_figure = QAction("Figure setup") self.menu_settings_figure.setShortcut('Ctrl+Alt+F') self.menu_settings_figure.setStatusTip('Figure setup') self.menu_settings_figure.setObjectName("menu_settings_figure") self.settings_menu.addAction(self.menu_settings_figure) # plot setup self.menu_settings_plot = QAction("Plot setup") self.menu_settings_plot.setShortcut('Ctrl+Alt+P') self.menu_settings_plot.setStatusTip('Plot setup') self.menu_settings_plot.setObjectName("menu_settings_plot") self.settings_menu.addAction(self.menu_settings_plot) self.settings_menu.addSeparator() # start point self.menu_start_point = QAction("Start point") self.menu_start_point.setShortcut('Ctrl+Alt+S') self.menu_start_point.setStatusTip('Set start point') self.menu_start_point.setObjectName("menu_start_point") self.settings_menu.addAction(self.menu_start_point) # speed self.menu_speed = QAction("Animation Speed") self.menu_speed.setShortcut('Ctrl+Alt+.') self.menu_speed.setStatusTip('Set animatio speed') self.menu_speed.setObjectName('menu_speed') self.settings_menu.addAction(self.menu_speed) # help menu self.help_menu = self.main_menu.addMenu('Help') self.help_menu.setObjectName("help_menu") # Manual self.menu_settings_manual = QAction("Manual") self.menu_settings_manual.setShortcut('Ctrl+Alt+M') self.menu_settings_manual.setStatusTip('Open Manual') self.menu_settings_manual.setObjectName("menu_settings_manual") self.help_menu.addAction(self.menu_settings_manual) # About self.menu_settings_about = QAction("About") self.menu_settings_about.setShortcut('Ctrl+Alt+A') self.menu_settings_about.setStatusTip('About this Programm') self.menu_settings_about.setObjectName("menu_settings_about") self.help_menu.addAction(self.menu_settings_about) def _left_side(self): """ Init left side objects: - Plot canvas - Player and settings buttons in layout and frame """ # plot label # Input layout for matplotlib canvas object self.verticalLayout_plot_canvas = QVBoxLayout() self.verticalLayout_plot_canvas.setObjectName( "verticalLayout_plot_canvas") self.verticalLayout_left.addLayout(self.verticalLayout_plot_canvas) # player button frame and layout self.frame_playerbuttons = QFrame() self.frame_playerbuttons.setObjectName("frame_playerbuttons") self.frame_playerbuttons.setFrameShape(QFrame.StyledPanel) self.frame_playerbuttons.setFrameShadow(QFrame.Plain) self.frame_playerbuttons.setLineWidth(10) self.verticalLayout_left.addWidget(self.frame_playerbuttons) self.verticalLayout_playerbottons = QHBoxLayout( self.frame_playerbuttons) self.verticalLayout_playerbottons.setObjectName( "verticalLayout_playerbottons") self._add_player_buttons() def _right_side(self): """ Init right side objects: - function / method combo boxes with layout and frames - function parameter display and button with layout and frame - method parameter display and button with layout and frame - pseudocode display - go and reset button with layput and frame """ # combo boxes frame and layouts # function/method self.frame_combo_boxes = QFrame() self.frame_combo_boxes.setObjectName("frame_combo_boxes") self.frame_combo_boxes.setFrameShape(QFrame.StyledPanel) self.frame_combo_boxes.setFrameShadow(QFrame.Plain) self.frame_combo_boxes.setLineWidth(10) self.frame_combo_boxes.setFixedSize(200, 70) self.verticalLayout_right.addWidget(self.frame_combo_boxes) self.verticalLayout_combo_boxes = QVBoxLayout(self.frame_combo_boxes) self.verticalLayout_combo_boxes.setObjectName( "verticalLayout_combo_boxes") # inner combo box frame layouts self.horizontalLayout_function = QHBoxLayout() self.horizontalLayout_function.setObjectName( "horizontalLayout_function") self.verticalLayout_combo_boxes.addLayout( self.horizontalLayout_function) self.horizontalLayout_method = QHBoxLayout() self.horizontalLayout_method.setObjectName("horizontalLayout_method") self.verticalLayout_combo_boxes.addLayout(self.horizontalLayout_method) # combo box and label function self.label_function = QLabel() self.label_function.setObjectName("label_function") self.label_function.setText("Function:") self.horizontalLayout_function.addWidget(self.label_function) self.horizontalLayout_function.setObjectName("label_function") self.comboBox_function = QComboBox(self.centralwidget) self.comboBox_function.setObjectName("comboBox_function") self.comboBox_function.addItem("") self.horizontalLayout_function.addWidget(self.comboBox_function) # combo box and label method self.label_method = QLabel() self.label_function.setObjectName("label_method") self.label_method.setText("Method:") self.horizontalLayout_method.addWidget(self.label_method) self.horizontalLayout_method.setObjectName("horizontalLayout_method") self.comboBox_method = QComboBox(self.centralwidget) self.comboBox_method.setObjectName("comboBox_method") self.comboBox_method.addItem("") self.horizontalLayout_method.addWidget(self.comboBox_method) # start point # frame and layout self.frame_start_point = QFrame() self.frame_start_point.setObjectName("frame_start_point") self.frame_start_point.setFrameShape(QFrame.StyledPanel) self.frame_start_point.setFrameShadow(QFrame.Plain) self.frame_start_point.setLineWidth(10) self.frame_start_point.setFixedSize(200, 40) self.verticalLayout_right.addWidget(self.frame_start_point) self.horizontalLayout_start_point = QHBoxLayout(self.frame_start_point) self.horizontalLayout_start_point.setObjectName( "horizontalLayout_start_point") # button self.button_set_start_point = QPushButton() self.button_set_start_point.setObjectName("button_set_start_point") self.button_set_start_point.setText("Set start point") self.horizontalLayout_start_point.addWidget( self.button_set_start_point) # label self.label_start_point = QLabel() self.label_start_point.setObjectName("label_start_point") self.label_start_point.setAlignment(Qt.AlignCenter) self.horizontalLayout_start_point.addWidget(self.label_start_point) # function parameters # function parameters frame and layout self.frame_function_parameters = QFrame() self.frame_function_parameters.setObjectName( "frame_function_parameters") self.frame_function_parameters.setFrameShape(QFrame.StyledPanel) self.frame_function_parameters.setFrameShadow(QFrame.Plain) self.frame_function_parameters.setLineWidth(10) self.frame_function_parameters.setFixedSize(200, 150) self.verticalLayout_right.addWidget(self.frame_function_parameters) self.verticalLayout_function_parameters = QVBoxLayout( self.frame_function_parameters) self.verticalLayout_function_parameters.setObjectName( "verticalLayout_function_parameters") # function parameter label self.label_function_parameters = QLabel() self.label_function_parameters.setObjectName( "label_function_parameters") self.label_function_parameters.setText("Parameterized function:") self.verticalLayout_function_parameters.addWidget( self.label_function_parameters) self.label_function_parameters_show = QLabel() self.label_function_parameters_show.setObjectName( "label_function_parameters_show") self.label_function_parameters_show.setFont(self.italic_font) self.label_function_parameters_show.setText(" not set yet") self.label_function_parameters_show.setFixedHeight(80) self.verticalLayout_function_parameters.addWidget( self.label_function_parameters_show) # with scrolling self.scroll_area_label_function = QScrollArea() self.scroll_area_label_function.setObjectName( "scroll_area_label_function") self.scroll_area_label_function.setWidgetResizable(True) self.scroll_area_label_function.setFixedHeight(80) self.scroll_area_label_function.setWidget( self.label_function_parameters_show) self.verticalLayout_function_parameters.addWidget( self.scroll_area_label_function) # function parameter button self.button_function_parameter = QPushButton() self.button_function_parameter.setObjectName( "button_function_parameter") self.button_function_parameter.setText("Set Parameters") self.verticalLayout_function_parameters.addWidget( self.button_function_parameter) # method parameters # method parameters frame and layout self.frame_method_parameters = QFrame() self.frame_method_parameters.setObjectName("frame_method_parameters") self.frame_method_parameters.setFrameShape(QFrame.StyledPanel) self.frame_method_parameters.setFrameShadow(QFrame.Plain) self.frame_method_parameters.setLineWidth(10) self.frame_method_parameters.setFixedSize(200, 150) self.verticalLayout_right.addWidget(self.frame_method_parameters) self.verticalLayout_method_parameters = QVBoxLayout( self.frame_method_parameters) self.verticalLayout_method_parameters.setObjectName( "verticalLayout_method_parameters") # method parameter label self.label_method_parameters = QLabel() self.label_method_parameters.setObjectName("label_method_parameters") self.label_method_parameters.setText("Method parameters:") self.verticalLayout_method_parameters.addWidget( self.label_method_parameters) self.label_method_parameters_show = QLabel() self.label_method_parameters_show.setObjectName( "label_method_parameters_show") self.label_method_parameters_show.setFont(self.italic_font) self.label_method_parameters_show.setText(" not set yet") self.label_method_parameters_show.setFixedHeight(80) self.verticalLayout_method_parameters.addWidget( self.label_method_parameters_show) # with scrolling self.scroll_area_label_method = QScrollArea() self.scroll_area_label_method.setObjectName("scroll_area_label_method") self.scroll_area_label_method.setWidgetResizable(True) self.scroll_area_label_method.setFixedHeight(80) self.scroll_area_label_method.setWidget( self.label_method_parameters_show) self.verticalLayout_method_parameters.addWidget( self.scroll_area_label_method) # method parameter button self.button_method_parameter = QPushButton() self.button_method_parameter.setObjectName("button_method_parameter") self.button_method_parameter.setText("Set Parameters") self.verticalLayout_method_parameters.addWidget( self.button_method_parameter) # pseudocode self.label_animation_pseudocode = PseudocodeHighlightAnimation() self.label_animation_pseudocode.setObjectName( "label_animation_pseudocode") self.verticalLayout_right.addWidget(self.label_animation_pseudocode) # show and reset button frame and layout self.frame_show_reset = QFrame() self.frame_show_reset.setObjectName("frame_show_reset") self.frame_show_reset.setFrameShape(QFrame.StyledPanel) self.frame_show_reset.setFrameShadow(QFrame.Plain) self.frame_show_reset.setLineWidth(10) self.frame_show_reset.setFixedSize(200, 90) self.verticalLayout_right.addWidget(self.frame_show_reset) self.verticalLayout_show_reset = QVBoxLayout(self.frame_show_reset) self.verticalLayout_show_reset.setObjectName( "verticalLayout_show_reset") # show button self.button_calculate = QPushButton() self.button_calculate.setObjectName("button_calculate") self.verticalLayout_show_reset.addWidget(self.button_calculate) self.button_calculate.setText('Calculate') # reset button self.button_reset = QPushButton() self.button_reset.setObjectName("button_reset") self.verticalLayout_show_reset.addWidget(self.button_reset) self.button_reset.setText('Reset') def _add_player_buttons(self): """ Init 'media' player buttons as well as all other buttons in this frame """ # player buttons size policy self.button_policy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) # first button self.button_first = QPushButton(self.centralwidget) self.button_first.setObjectName("button_first") self.first_icon = QIcon(module_dir + 'gui_imgs/first.png') self.button_first.setIcon(self.first_icon) self.button_first.setIconSize(QSize(35, 35)) self.button_first.setFlat(True) self.verticalLayout_playerbottons.addWidget(self.button_first, alignment=Qt.AlignRight) # previous button self.button_prev = QPushButton(self.centralwidget) self.button_prev.setObjectName("button_prev") self.prev_icon = QIcon(module_dir + 'gui_imgs/prev.png') self.button_prev.setIcon(self.prev_icon) self.button_prev.setIconSize(QSize(50, 50)) self.button_prev.setFlat(True) self.verticalLayout_playerbottons.addWidget(self.button_prev, alignment=Qt.AlignLeft) # play / pause button self.button_play_pause = QPushButton(self.centralwidget) self.button_play_pause.setObjectName("button_play_pause") self.button_play_pause_icon = QIcon(module_dir + 'gui_imgs/play.png') self.button_play_pause.setIcon(self.button_play_pause_icon) self.button_play_pause.setIconSize(QSize(55, 55)) self.button_play_pause.setFlat(True) self.verticalLayout_playerbottons.addWidget(self.button_play_pause, alignment=Qt.AlignCenter) # next button self.button_next = QPushButton(self.centralwidget) self.button_next.setObjectName("button_next") self.next_icon = QIcon(module_dir + 'gui_imgs/next.png') self.button_next.setIcon(self.next_icon) self.button_next.setIconSize(QSize(50, 50)) self.button_next.setFlat(True) self.verticalLayout_playerbottons.addWidget(self.button_next, alignment=Qt.AlignRight) # last button self.button_last = QPushButton(self.centralwidget) self.button_last.setObjectName("button_last") self.last_icon = QIcon(module_dir + 'gui_imgs/last.png') self.button_last.setIcon(self.last_icon) self.button_last.setIconSize(QSize(35, 35)) self.button_last.setFlat(True) self.verticalLayout_playerbottons.addWidget(self.button_last, alignment=Qt.AlignLeft) # array position and xy mouse coords self.verticalLayout_pos_xy = QVBoxLayout() self.verticalLayout_pos_xy.setObjectName("verticalLayout_pos_xy") self.verticalLayout_playerbottons.addLayout(self.verticalLayout_pos_xy) # array position self.horizontalLayout_array_position = QHBoxLayout() self.horizontalLayout_array_position.setObjectName( "horizontalLayout_startpoint") self.horizontalLayout_array_position.setSizeConstraint( QVBoxLayout.SetFixedSize) self.verticalLayout_pos_xy.addLayout( self.horizontalLayout_array_position) # array position spinbox self.spinbox_currentposition = QSpinBox() self.spinbox_currentposition.setObjectName("spinbox_currentposition") self.spinbox_currentposition.setValue(0) self.spinbox_currentposition.setMaximum(0) self.horizontalLayout_array_position.addWidget( self.spinbox_currentposition) # array length lable self.label_arraylength = QLabel() self.label_arraylength.setObjectName("label_arraylength") self.label_arraylength.setText("/ -") self.horizontalLayout_array_position.addWidget(self.label_arraylength) # xy cords self.label_xy = QLabel() self.label_xy.setObjectName("label_xy") self.label_xy.setText("x: | y:") self.verticalLayout_pos_xy.addWidget(self.label_xy) # speed control self.verticalLayout_speed = QVBoxLayout() self.verticalLayout_playerbottons.addLayout(self.verticalLayout_speed) # slow fast label self.label_speed = QLabel() self.label_speed.setText("slow fast") self.label_speed.setAlignment(Qt.AlignBottom) self.verticalLayout_speed.addWidget(self.label_speed) # slider self.slider_speed = QSlider(Qt.Horizontal) self.slider_speed.setObjectName("slider_speed") self.slider_speed.setTickInterval(25) self.slider_speed.setFixedSize(75, 20) self.slider_speed.setSingleStep(1) self.slider_speed.setValue(50) self.slider_speed.setTickPosition(QSlider.NoTicks) self.verticalLayout_speed.addWidget(self.slider_speed) def _presets(self, MainWindow): """ Helper variables to be used in object inits :param MainWindow: MainWindow object. see main.py and guis_event_handler.py for further information """ self.italic_font = QFont() self.italic_font.setItalic(True) self.non_italic_font = QFont() self.non_italic_font.setItalic(False) self.MainWindow = MainWindow def _postsets(self): """ No Idea what this is doing """ self.MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QStatusBar(self.MainWindow) self.statusbar.setObjectName("statusbar") self.MainWindow.setStatusBar(self.statusbar) QMetaObject.connectSlotsByName(self.MainWindow) def set_pseudocode(self, pseudocode_pos): """ Sets the pseudo code picture anew :param pseudocode_pos: current pseudo code line number """ self.label_animation_pseudocode.move(pseudocode_pos)
class Ui_MainWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.transprot_mass =[] self.netprot_mass =[] self.filtering_is_on = 0 grid = QGridLayout() self.setLayout(grid) self.IP_list = IP_list(self) self.TransProt_list = TransProt_list(self) self.NetProt_list = NetProt_list(self) self.setWindowTitle('Гамма') self.setWindowIcon(QIcon('допочки\Gamma_200x200.png')) self.resize(740, 830) self.to_center() self.centralwidget = QWidget(self) self.tabWidget = QTabWidget(self.centralwidget) self.tabWidget.setGeometry(QRect(20, 20, 700, 750)) self.tab = QWidget() grid.addWidget(self.tab) self.cb_time = QCheckBox(self.tab) self.cb_time.setGeometry(QRect(360, 130, 120, 20)) self.cb_time.setText("Фильтр по времени") self.cb_prot = QCheckBox(self.tab) self.cb_prot.setGeometry(QRect(20, 130, 140, 20)) self.cb_prot.setText("Фильтр по протоколам") self.cb_addr = QCheckBox(self.tab) self.cb_addr.setGeometry(QRect(360, 290, 130, 20)) self.cb_addr.setText("Фильтр по IP-адресам") self.dt_beg = QDateTimeEdit(self.tab) self.dt_beg.setGeometry(QRect(360, 210, 150, 20)) self.dt_beg.setDateTime(QDateTime.currentDateTime()) self.dt_beg.setDisplayFormat("dd.MM.yyyy H:mm:ss.zzz") self.dt_beg.setCalendarPopup(True) self.dt_beg.setToolTip('Выбрать начальное время (>=)') self.dt_beg.setEnabled(False) self.dt_end = QDateTimeEdit(self.tab) self.dt_end.setGeometry(QRect(520, 210, 150, 20)) self.dt_end.setDateTime(QDateTime.currentDateTime()) self.dt_end.setDisplayFormat("dd.MM.yyyy H:mm:ss.zzz") self.dt_end.setCalendarPopup(True) self.dt_end.setToolTip('Выбрать конечное время (<)') self.dt_end.setEnabled(False) self.dt_beg.dateChanged.connect(lambda dc: self.date_changed(1)) self.dt_end.dateChanged.connect(lambda dc: self.date_changed(2)) #self.l_input_dir = QLabel(self.tab) #self.l_input_dir.setGeometry(QRect(102, 50, 180, 15)) #self.l_input_dir.setText("Выберите директорию с файлами") #self.l_or = QLabel(self.tab) #self.l_or.setGeometry(QRect(340, 50, 21, 16)) #self.l_or.setText("ИЛИ") self.l_input_file = QLabel(self.tab) self.l_input_file.setGeometry(QRect(300, 50, 90, 15)) self.l_input_file.setText("Выберите файлы") self.l_transpr = QLabel(self.tab) self.l_transpr.setGeometry(QRect(50, 190, 180, 16)) self.l_transpr.setEnabled(False) self.l_transpr.setText("Протоколы Транспортного уровня") self.l_netpr = QLabel(self.tab) self.l_netpr.setGeometry(QRect(50, 290, 180, 16)) self.l_netpr.setEnabled(False) self.l_netpr.setText("Протоколы Сетевого уровня") self.l_beg = QLabel(self.tab) self.l_beg.setGeometry(QRect(390, 190, 60, 16)) self.l_beg.setEnabled(False) self.l_beg.setText("Начиная с..") self.l_end = QLabel(self.tab) self.l_end.setGeometry(QRect(560, 190, 80, 16)) self.l_end.setEnabled(False) self.l_end.setText("Оканчивая до..") self.l_name = QLabel(self.tab) self.l_name.setGeometry(QRect(300, 450, 96, 16)) self.l_name.setText("Как назвать файл?") self.l_filt = QLabel(self.tab) self.l_filt.setGeometry(QRect(300, 10, 91, 16)) self.l_filt.setText("Выборка пакетов") self.line = QFrame(self.tab) self.line.setGeometry(QRect(0, 110, 690, 15)) self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.line_2 = QFrame(self.tab) self.line_2.setGeometry(QRect(340, 120, 15, 300)) self.line_2.setFrameShape(QFrame.VLine) self.line_2.setFrameShadow(QFrame.Sunken) self.line_3 = QFrame(self.tab) self.line_3.setGeometry(QRect(0, 420, 690, 15)) self.line_3.setFrameShape(QFrame.HLine) self.line_3.setFrameShadow(QFrame.Sunken) #self.le_dir = QLineEdit(self.tab) #self.le_dir.setGeometry(QRect(110, 80, 211, 20)) #self.le_dir.setEnabled(False) #self.le_dir.setReadOnly(True) self.le_file = QLineEdit(self.tab) self.le_file.setGeometry(QRect(250, 80, 211, 20)) #self.le_file.setEnabled(False) self.le_file.setReadOnly(True) self.le_name = QLineEdit(self.tab) self.le_name.setGeometry(QRect(250, 480, 231, 20)) self.pt_transpr = QPlainTextEdit(self.tab) self.pt_transpr.setGeometry(QRect(50, 210, 271, 71)) self.pt_transpr.setEnabled(False) self.pt_transpr.setReadOnly(True) self.pt_netpr = QPlainTextEdit(self.tab) self.pt_netpr.setGeometry(QRect(50, 320, 271, 71)) self.pt_netpr.setEnabled(False) self.pt_netpr.setReadOnly(True) self.pt_addr = QPlainTextEdit(self.tab) self.pt_addr.setGeometry(QRect(390, 320, 271, 71)) self.pt_addr.setEnabled(False) self.pt_log = QPlainTextEdit(self.tab) self.pt_log.setGeometry(QRect(20, 610, 651, 101)) self.pt_log.setReadOnly(True) self.progressBar = QProgressBar(self.tab) self.progressBar.setGeometry(QRect(20, 580, 651, 20)) self.progressBar.setFormat("%v" + "%") self.progressBar.setMaximum(100) self.progressBar.setValue(0) #self.pb_dir = QPushButton(self.tab) #self.pb_dir.setGeometry(QRect(80, 80, 21, 20)) #self.pb_dir.setIcon(QIcon('допочки\_folder.png')) #self.pb_dir.clicked.connect(lambda gd: self.get_directory(1)) self.pb_file = QPushButton(self.tab) self.pb_file.setGeometry(QRect(220, 80, 21, 20)) self.pb_file.setIcon(QIcon('допочки\_folder.png')) self.pb_file.clicked.connect(lambda gf: self.get_files(1)) self.pb_time = QPushButton(self.tab) self.pb_time.setGeometry(QRect(480, 240, 71, 20)) self.pb_time.setToolTip('Добавить ещё временной отрезок') self.pb_time.setEnabled(False) self.pb_time.setText("Ещё!") self.pb_transpr = QPushButton(self.tab) self.pb_transpr.setGeometry(QRect(20, 210, 21, 20)) self.pb_transpr.setToolTip('Выбрать протоколы Транспортного уровня') self.pb_transpr.setIcon(QIcon('допочки\_blank.png')) self.pb_transpr.setEnabled(False) self.pb_transpr.clicked.connect(self.TransProt_list.exec) self.pb_netpr = QPushButton(self.tab) self.pb_netpr.setGeometry(QRect(20, 320, 21, 20)) self.pb_netpr.setToolTip('Выбрать протоколы Сетевого уровня') self.pb_netpr.setIcon(QIcon('допочки\_blank.png')) self.pb_netpr.setEnabled(False) self.pb_netpr.clicked.connect(self.NetProt_list.exec) self.pb_addr = QPushButton(self.tab) self.pb_addr.setGeometry(QRect(530, 290, 132, 20)) self.pb_addr.setText('Редактировать список') self.pb_addr.setEnabled(False) self.pb_addr.clicked.connect(self.IP_list.exec) self.pb_name = QPushButton(self.tab) self.pb_name.setGeometry(QRect(220, 480, 21, 20)) self.pb_name.setIcon(QIcon('допочки\_folder.png')) self.pb_name.clicked.connect(lambda ed: self.extract_to_directory(1)) self.pb_start = QPushButton(self.tab) self.pb_start.setGeometry(QRect(220, 510, 261, 41)) self.pb_start.setText("Начать выборку") self.pb_start.clicked.connect(self.do_it_motherFucker) #self.radiobutton = QRadioButton(self.tab) #self.radiobutton.setGeometry(QRect(84, 48, 20, 20)) #self.radiobutton_2 = QRadioButton(self.tab) #self.radiobutton_2.setGeometry(QRect(424, 48, 20, 20)) #self.radiobutton.raise_() #self.radiobutton_2.raise_() self.cb_time.raise_() self.cb_prot.raise_() self.cb_addr.raise_() self.dt_beg.raise_() self.dt_end.raise_() #self.l_input_dir.raise_() #self.l_or.raise_() self.l_input_file.raise_() self.l_transpr.raise_() self.l_netpr.raise_() self.l_beg.raise_() self.l_end.raise_() self.l_name.raise_() self.l_filt.raise_() self.line.raise_() self.line_2.raise_() self.line_3.raise_() #self.le_dir.raise_() self.le_file.raise_() self.le_name.raise_() self.pt_transpr.raise_() self.pt_netpr.raise_() self.pt_addr.raise_() self.pt_log.raise_() self.progressBar.raise_() #self.pb_dir.raise_() self.pb_file.raise_() self.pb_time.raise_() self.pb_transpr.raise_() self.pb_netpr.raise_() self.pb_addr.raise_() self.pb_name.raise_() self.pb_start.raise_() self.setCentralWidget(self.centralwidget) self.statusbar = QStatusBar(self) self.setStatusBar(self.statusbar) self.tabWidget.addTab(self.tab, "") self.cb_time.clicked['bool'].connect(self.dt_beg.setEnabled) self.cb_time.clicked['bool'].connect(self.dt_end.setEnabled) self.cb_time.clicked['bool'].connect(self.l_beg.setEnabled) self.cb_time.clicked['bool'].connect(self.l_end.setEnabled) self.cb_prot.clicked['bool'].connect(self.l_transpr.setEnabled) self.cb_prot.clicked['bool'].connect(self.l_netpr.setEnabled) self.cb_prot.clicked['bool'].connect(self.pt_transpr.setEnabled) self.cb_prot.clicked['bool'].connect(self.pt_netpr.setEnabled) self.cb_prot.clicked['bool'].connect(self.pb_transpr.setEnabled) self.cb_prot.clicked['bool'].connect(self.pb_netpr.setEnabled) self.cb_addr.clicked['bool'].connect(self.pt_addr.setEnabled) self.cb_addr.clicked['bool'].connect(self.pb_addr.setEnabled) #####------------------------------2_TAB self.tab_2 = QWidget() self.tabWidget.addTab(self.tab_2, "") self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), ("II работа с файлами")) self.l_merge = QLabel(self.tab_2) self.l_merge.setGeometry(QRect(300, 10, 180, 16)) self.l_merge.setText("Объединение файлов") self.l_arch = QLabel(self.tab_2) self.l_arch.setGeometry(QRect(300, 250, 180, 16)) self.l_arch.setText("Архивирование файлов") #self.radiobutton_3 = QRadioButton(self.tab_2) #self.radiobutton_3.setGeometry(QRect(84, 48, 20, 20)) #self.radiobutton_4 = QRadioButton(self.tab_2) #self.radiobutton_4.setGeometry(QRect(424, 48, 20, 20)) #self.l_input_dir2 = QLabel(self.tab_2) #self.l_input_dir2.setGeometry(QRect(102, 50, 180, 15)) #self.l_input_dir2.setText("Выберите директорию с файлами") #self.l_or2 = QLabel(self.tab_2) #self.l_or2.setGeometry(QRect(340, 50, 21, 16)) #self.l_or2.setText("ИЛИ") self.l_input_file2 = QLabel(self.tab_2) self.l_input_file2.setGeometry(QRect(102, 50, 180, 15))#442, 50, 90, 15)) self.l_input_file2.setText("Выберите файлы") self.l_name2 = QLabel(self.tab_2) self.l_name2.setGeometry(QRect(442, 50, 180, 15))#280, 140, 180, 16)) self.l_name2.setText("Куда сохранить результат?") self.l_ciph2 = QLabel(self.tab_2) self.l_ciph2.setGeometry(QRect(84, 298, 180, 15)) self.l_ciph2.setText("Убрать шифрованный трафик") self.l_arch2 = QLabel(self.tab_2) self.l_arch2.setGeometry(QRect(424, 298, 180, 15)) self.l_arch2.setText("Заархивировать файлы") #self.le_dir2 = QLineEdit(self.tab_2) #self.le_dir2.setGeometry(QRect(110, 80, 211, 20)) #self.le_dir2.setEnabled(False) self.le_file2 = QLineEdit(self.tab_2) self.le_file2.setGeometry(QRect(110, 80, 211, 20))#450, 80, 211, 20)) self.le_file2.setReadOnly(True) self.le_name2 = QLineEdit(self.tab_2) self.le_name2.setGeometry(QRect(450, 80, 211, 20))#260, 170, 180, 20)) #self.pb_dir2 = QPushButton(self.tab_2) #self.pb_dir2.setGeometry(QRect(80, 80, 21, 20)) #self.pb_dir2.setIcon(QIcon('допочки\_folder.png')) #self.pb_dir2.clicked.connect(lambda gd: self.get_directory(2)) self.pb_file2 = QPushButton(self.tab_2) self.pb_file2.setGeometry(QRect(80, 80, 21, 20))#420, 80, 21, 20)) self.pb_file2.setIcon(QIcon('допочки\_folder.png')) self.pb_file2.clicked.connect(lambda gf: self.get_files(2)) self.pb_name2 = QPushButton(self.tab_2) self.pb_name2.setGeometry(QRect(420, 80, 21, 20))#230, 170, 21, 20)) self.pb_name2.setIcon(QIcon('допочки\_folder.png')) self.pb_name2.clicked.connect(lambda ed: self.extract_to_directory(2)) self.pb_merge = QPushButton(self.tab_2) self.pb_merge.setGeometry(QRect(270, 170, 160, 20)) self.pb_merge.setText("Объединить") self.pb_merge.clicked.connect(self.merge_it_motherFucker) self.line_4 = QFrame(self.tab_2) self.line_4.setGeometry(QRect(0, 280, 690, 15)) self.line_4.setFrameShape(QFrame.HLine) self.line_4.setFrameShadow(QFrame.Sunken) self.line_5 = QFrame(self.tab_2) self.line_5.setGeometry(QRect(0, 580, 690, 15)) self.line_5.setFrameShape(QFrame.HLine) self.line_5.setFrameShadow(QFrame.Sunken) self.pt_log2 = QPlainTextEdit(self.tab_2) self.pt_log2.setGeometry(QRect(20, 610, 651, 101)) self.pt_log2.setReadOnly(True) self.graphicsView = QGraphicsView(self.tab_2) self.graphicsView.setGeometry(QRect(0, 330, 714, 277)) self.scene = QGraphicsScene() self.graphicsView.setScene(self.scene) self.scene.addPixmap(QPixmap('допочки\_in_working_3.png')) self.l_merge.raise_() self.l_arch.raise_() #self.l_input_dir2.raise_() #self.l_or2.raise_() self.l_input_file2.raise_() self.l_name2.raise_() #self.radiobutton_3.raise_() #self.radiobutton_4.raise_() #self.pb_dir2.raise_() self.pb_file2.raise_() self.pb_name2.raise_() #self.le_dir2.raise_() self.le_file2.raise_() self.le_name2.raise_() self.line_4.raise_() self.line_5.raise_() self.pt_log2.raise_() #####------------------------------2_TAB #####------------------------------3_TAB self.tab_3 = QWidget() self.tabWidget.addTab(self.tab_3, "") self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), ("III Проверка на аномальную активность")) self.tab_3.setEnabled(False) self.l_filt3 = QLabel(self.tab_3) self.l_filt3.setGeometry(QRect(300, 10, 91, 16)) self.l_filt3.setText("Выборка пакетов") self.l_input_file3 = QLabel(self.tab_3) self.l_input_file3.setGeometry(QRect(300, 50, 90, 15)) self.l_input_file3.setText("Выберите файлы") self.pb_file3 = QPushButton(self.tab_3) self.pb_file3.setGeometry(QRect(220, 80, 21, 20)) self.pb_file3.setIcon(QIcon('допочки\_folder.png')) self.pb_file3.clicked.connect(lambda gf: self.get_files(3)) self.le_file3 = QLineEdit(self.tab_3) self.le_file3.setGeometry(QRect(250, 80, 211, 20)) self.le_file3.setReadOnly(True) self.pb_graphy = QPushButton(self.tab_3) self.pb_graphy.setGeometry(QRect(270, 170, 160, 20)) self.pb_graphy.setText("Построить граф") #self.pb_graphy.clicked.connect(self.graph_it) #self.label_6 = QLabel(self.tab_3) #self.pixmap = QPixmap('допочки\_in_working_1.png') #self.label_6.setPixmap(self.pixmap) self.l_filt3.raise_() self.l_input_file3.raise_() self.pb_file3.raise_() self.le_file3.raise_() #####------------------------------3_TAB #####----------------------------IN_WORK self.tab_4 = QWidget() self.tabWidget.addTab(self.tab_4, "") self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), ("...IV visualization...")) self.tab_4.setEnabled(False) self.label_7 = QLabel(self.tab_4) self.pixmap_2 = QPixmap('допочки\_in_working_2.png') self.label_7.setPixmap(self.pixmap_2) #####----------------------------IN_WORK self.tabWidget.setCurrentIndex(0) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), ("I выборка пакетов")) QMetaObject.connectSlotsByName(self) self.show() def closeEvent(self, event): reply = QMessageBox.question(self, 'Ща закроется всё', "Ты чо, реально хочешь выйти?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore() def to_center(self): qr = self.frameGeometry() qr.moveCenter(QDesktopWidget().availableGeometry().center()) self.move(qr.topLeft()) def get_directory(self, gd): if gd == 1: result = QFileDialog.getExistingDirectory() #self.le_dir.setText(result) self.le_file.setDisabled(True) #self.le_dir.setEnabled(True) #self.radiobutton_2.setChecked(False) #self.radiobutton.setChecked(True) else: result = QFileDialog.getExistingDirectory() #self.le_dir2.setText(result) self.le_file2.setDisabled(True) #self.le_dir2.setEnabled(True) #self.radiobutton_4.setChecked(False) #self.radiobutton_3.setChecked(True) def get_files(self, gf): if gf == 1: result, bullshit = QFileDialog.getOpenFileNames(self, "Выберите pcap-файлы", getcwd(), "files (*.pcap *.pcapng)") #self.le_dir.setDisabled(True) self.le_file.setEnabled(True) #self.radiobutton.setChecked(False) #self.radiobutton_2.setChecked(True) if len(result): self.le_file.setText(", ".join(result)) elif gf == 3: result, bullshit = QFileDialog.getOpenFileNames(self, "Выберите pcap-файлы", getcwd(), "files (*.pcap *.pcapng)") #self.le_dir.setDisabled(True) self.le_file3.setEnabled(True) #self.radiobutton.setChecked(False) #self.radiobutton_2.setChecked(True) if len(result): self.le_file3.setText(", ".join(result)) else: result, bullshit = QFileDialog.getOpenFileNames(self, "Выберите pcap-файлы", getcwd(), "files (*.pcap *.pcapng)") #self.le_dir2.setDisabled(True) self.le_file2.setEnabled(True) #self.radiobutton_3.setChecked(False) #self.radiobutton_4.setChecked(True) if len(result): self.le_file2.setText(", ".join(result)) def date_changed(self, dc): if dc == 1: self.dt_end.setMinimumDateTime(QDateTime(self.dt_beg.dateTime())) else: self.dt_beg.setMaximumDateTime(QDateTime(self.dt_end.dateTime())) def extract_to_directory(self, ed): if ed == 1: result, bullshit =QFileDialog.getSaveFileName(self, "Сохранить файл", getcwd(), "files (*.pcap *.pcapng)") self.le_name.setText(result) else: result, bullshit =QFileDialog.getSaveFileName(self, "Сохранить файл", getcwd(), "files (*.pcap *.pcapng)") self.le_name2.setText(result) def do_it_motherFucker(self): if self.filtering_is_on == 0: #if ((not self.radiobutton.isChecked() and not self.radiobutton_2.isChecked())\ # or (self.radiobutton.isChecked() and self.le_dir.text() == '')\ # or (self.radiobutton_2.isChecked() and self.le_file.text() == ''))\ # and self.le_name.text() == '': if self.le_file.text() == '' and self.le_name.text() == '': self.pt_log.appendPlainText(" " + "Какие файлы обработать? Куда сохранить? Такая неопределённость..") #elif (not self.radiobutton.isChecked() and not self.radiobutton_2.isChecked()) or (self.radiobutton.isChecked() and self.le_dir.text() == '') or (self.radiobutton_2.isChecked() and self.le_file.text() == ''): elif self.le_file.text() == '': self.pt_log.appendPlainText(" " + "Какие файлы обработать?") elif self.le_name.text() == '': self.pt_log.appendPlainText(" " + "Куда сохранить?") else: self.filtering_is_on = 1 # эти пиздецы в идеале нужно заменить на что-нибудь адекватное self.count_for_pr_b = 0 # эти пиздецы в идеале нужно заменить на что-нибудь адекватное self.progressBar.setValue(0) self.pb_start.setText("Остановить выборку") #my_directory = self.le_dir.text() pcap_files_in = self.le_file.text() pcap_file_out = self.le_name.text() per_quest = 0 per_beg = '' per_end = '' prot_quest = 0 net_prot = 0 trans_prot = 0 appl_prot = 0 ## ip_quest = 0 netprot_mass = [] transprot_mass = [] addr_mass = [] if (pcap_file_out.endswith(".pcap") or pcap_file_out.endswith(".pcapng")) == False: pcap_file_out = pcap_file_out + ".pcap" self.pt_log.appendPlainText("Сохранить в:") self.pt_log.appendPlainText(" " + pcap_file_out) #if self.radiobutton.isChecked(): # onlyfiles = [my_directory + '/' + f for f in listdir(my_directory) if # f.endswith(".pcap") or f.endswith(".pcapng") and isfile(join(my_directory, f))] # self.for_pr_b = len(onlyfiles) # # self.pt_log.appendPlainText("Выбрана директория:") # self.pt_log.appendPlainText(" " + self.le_dir.text()) # self.pt_log.appendPlainText("С pcap-файлами:") # for file in onlyfiles: # bullshit, fname = file.rsplit('/', 1) # self.pt_log.appendPlainText(" " + fname) #elif self.radiobutton_2.isChecked(): onlyfiles = pcap_files_in.split(', ') self.for_pr_b = len(onlyfiles) self.pt_log.appendPlainText("Выбраны pcap-файлы:") for file in onlyfiles: self.pt_log.appendPlainText(" " + (file)) if self.cb_addr.isChecked() and self.pt_addr.toPlainText() != '': ip_quest = 1 addr_mass = self.pt_addr.toPlainText().splitlines() if self.cb_time.isChecked(): per_quest = 1 per_beg = self.dt_beg.dateTime() per_end = self.dt_end.dateTime() if self.cb_prot.isChecked(): prot_quest = 1 transprot_mass = self.transprot_mass netprot_mass = self.netprot_mass if self.pt_transpr.toPlainText() != '': trans_prot = 1 if self.pt_netpr.toPlainText() != '': net_prot = 1 #self.radiobutton.setDisabled(True) #self.radiobutton_2.setDisabled(True) #self.l_input_dir.setDisabled(True) #self.l_or.setDisabled(True) self.l_input_file.setDisabled(True) #self.pb_dir.setDisabled(True) self.pb_file.setDisabled(True) #self.le_dir.setDisabled(True) self.le_file.setDisabled(True) self.cb_time.setDisabled(True) self.cb_prot.setDisabled(True) self.cb_addr.setDisabled(True) self.l_transpr.setDisabled(True) self.l_netpr.setDisabled(True) self.l_beg.setDisabled(True) self.l_end.setDisabled(True) self.l_name.setDisabled(True) self.l_filt.setDisabled(True) self.le_name.setDisabled(True) self.dt_beg.setDisabled(True) self.dt_end.setDisabled(True) self.pt_transpr.setDisabled(True) self.pt_netpr.setDisabled(True) self.pt_addr.setDisabled(True) self.pb_time.setDisabled(True) self.pb_transpr.setDisabled(True) self.pb_netpr.setDisabled(True) self.pb_addr.setDisabled(True) self.pb_name.setDisabled(True) self.worker = WorkerThread(onlyfiles, pcap_file_out, per_quest, per_beg, per_end, prot_quest, net_prot, netprot_mass, trans_prot, transprot_mass, appl_prot, ip_quest, addr_mass) self.worker.callback_received.connect(self.append_to_log) self.worker.start() self.pt_log.appendPlainText("") self.pt_log.appendPlainText("В работе:") elif self.filtering_is_on == 1: self.worker.terminate() self.pt_log.appendPlainText("") self.pt_log.appendPlainText("Работа прервана") self.pt_log.appendPlainText("") self.pt_log.appendPlainText("") self.go_to_starting_set() def append_to_log(self, x): self.count_for_pr_b += 1 self.pt_log.appendPlainText("") self.pt_log.appendPlainText(x) self.progressBar.setValue(self.count_for_pr_b * 100 / (self.for_pr_b + 1)) if self.progressBar.value() == 100: self.pt_log.appendPlainText("") self.pt_log.appendPlainText("") self.go_to_starting_set() def go_to_starting_set(self): self.filtering_is_on = 0 self.pb_start.setText("Начать выборку") #self.radiobutton.setDisabled(False) #self.radiobutton_2.setDisabled(False) #self.l_input_dir.setDisabled(False) #self.l_or.setDisabled(False) self.l_input_file.setDisabled(False) #self.pb_dir.setDisabled(False) self.pb_file.setDisabled(False) #self.le_dir.setDisabled(False) self.le_file.setDisabled(False) self.cb_time.setDisabled(False) self.cb_prot.setDisabled(False) self.cb_addr.setDisabled(False) self.l_name.setDisabled(False) self.l_filt.setDisabled(False) self.le_name.setDisabled(False) self.pb_name.setDisabled(False) if self.cb_time.isChecked(): self.dt_beg.setEnabled(True) self.dt_end.setEnabled(True) self.l_beg.setEnabled(True) self.l_end.setEnabled(True) if self.cb_prot.isChecked(): self.l_transpr.setEnabled(True) self.l_netpr.setEnabled(True) self.pt_transpr.setEnabled(True) self.pt_netpr.setEnabled(True) self.pb_transpr.setEnabled(True) self.pb_netpr.setEnabled(True) if self.cb_addr.isChecked(): self.pt_addr.setEnabled(True) self.pb_addr.setEnabled(True) def merge_it_motherFucker(self): #if self.radiobutton_3.isChecked(): # self.pt_log2.appendPlainText("Выбрана директория с pcap-файлами:") # self.pt_log2.appendPlainText(" " + self.le_dir2.text()) # self.pt_log2.appendPlainText('Просматриваем "{}"...'.format(self.le_dir2.text())) # onlyfiles = [self.le_dir2.text() + '/' + f for f in listdir(self.le_dir2.text()) if # f.endswith(".pcap") or f.endswith(".pcapng") and isfile(join(self.le_dir2.text(), f))] # self.pt_log2.appendPlainText(str(onlyfiles)) #elif self.radiobutton_4.isChecked(): self.pt_log2.appendPlainText("Выбраны pcap-файлы:") self.pt_log2.appendPlainText(" " + self.le_file2.text()) onlyfiles = self.le_file2.text().split(', ') self.pt_log2.appendPlainText('Работаем с "{}"...'.format(onlyfiles)) merge_file_out = self.le_name2.text() if (merge_file_out.endswith(".pcap") or merge_file_out.endswith(".pcapng")) == False: merge_file_out = merge_file_out + ".pcap" self.pt_log2.appendPlainText("Сохранить в:") self.pt_log2.appendPlainText(" " + merge_file_out) self.pt_log2.appendPlainText("") merge.mergecap(onlyfiles, merge_file_out)
class NorSetTab(QWidget): def __init__(self, gui): super(NorSetTab, self).__init__() self._ui = gui self._tran = self._ui.tran self._config = self._ui.config self._parser = self._ui.configparser self._thread = None self._running = False self.setObjectName("settab") self._layout = QGridLayout(self) self._layout.setObjectName('settab_layout') # label for the plaintext directory self._label_clear = QLabel(self) self._label_clear.setObjectName('settab_label_clear') self._label_clear.setText(self._tran.get_text(self._label_clear.objectName())) # plaintext input self._input_clear = QLineEdit(self) self._input_clear.setObjectName('settab_input_clear') self._input_clear.setText('') self._input_clear.setReadOnly(True) self._input_clear.textChanged.connect(lambda: self._config.update({cc_con.SCR_DIR: self._input_clear.text()})) # plaintext button self._button_clear = QPushButton(self) self._button_clear.setObjectName('settab_button_clear') self._button_clear.setText(self._tran.get_text(self._button_clear.objectName())) self._button_clear.clicked.connect(self._browse_clear_dir) # label for the enc directory self._label_enc = QLabel(self) self._label_enc.setObjectName('settab_label_enc') self._label_enc.setText(self._tran.get_text(self._label_enc.objectName())) # enc input self._input_enc = QLineEdit(self) self._input_enc.setObjectName('settab_input_enc') self._input_enc.setReadOnly(True) self._input_enc.textChanged.connect(lambda: self._config.update({cc_con.DST_DIR: self._input_enc.text()})) # enc button self._button_enc = QPushButton(self) self._button_enc.setObjectName('settab_button_enc') self._button_enc.setText(self._tran.get_text(self._button_enc.objectName())) self._button_enc.clicked.connect(self._browse_enc_dir) # label for the key self._label_key1 = QLabel(self) self._label_key1.setObjectName("settab_label_key1") self._label_key1.setText(self._tran.get_text(self._label_key1.objectName())) # set up the input field for the password self._input_key1 = QLineEdit(self) self._input_key1.setObjectName("settab_tab_input_key1") self._input_key1.setEchoMode(QLineEdit.Password) self._input_key1.textChanged.connect(self._verify_passwords) # set up the show password button for key1 self._button_key1 = QPushButton(self) self._button_key1.setObjectName('settab_button_key1') self._button_key1.setText(self._tran.get_text(self._button_key1.objectName())) self._button_key1.pressed.connect(lambda: self._toggle_password(self._input_key1)) self._button_key1.released.connect(lambda: self._toggle_password(self._input_key1)) # set up the label for the key confirmation field self._label_key2 = QLabel(self) self._label_key2.setObjectName("settab_label_key2") self._label_key2.setText(self._tran.get_text(self._label_key2.objectName())) # set up the input field for the password confirmation self._input_key2 = QLineEdit(self) self._input_key2.setObjectName("settab_tab_input_key2") self._input_key2.setEchoMode(QLineEdit.Password) self._input_key2.textChanged.connect(self._verify_passwords) # setup the show password button for the password comfirmation self._button_key2 = QPushButton(self) self._button_key2.setObjectName('settab_button_key2') self._button_key2.setText(self._tran.get_text(self._button_key2.objectName())) self._button_key2.pressed.connect(lambda: self._toggle_password(self._input_key2)) self._button_key2.released.connect(lambda: self._toggle_password(self._input_key2)) # widget that is holding the slider self._widget_slider = QWidget(self) self._widget_slider.setObjectName('settab_widget_slider') # layout of the widget that is holding the slider self._widget_slider_layout = QGridLayout(self._widget_slider) self._widget_slider_layout.setObjectName('settab_widget_slider_layout') self._widget_slider.setLayout(self._widget_slider_layout) # left label of the slider self._label_left_slider = QLabel(self._widget_slider) self._label_left_slider.setObjectName('settab_label_left_slider') self._label_left_slider.setText(self._tran.get_text(self._label_left_slider.objectName())) self._label_left_slider.setAlignment(Qt.AlignRight | Qt.AlignVCenter) # right label of the slider self._label_right_slider = QLabel(self._widget_slider) self._label_right_slider.setObjectName('settab_label_right_slider') self._label_right_slider.setText(self._tran.get_text(self._label_right_slider.objectName())) # setup the slider itself self._slider = QSlider(self._widget_slider) self._slider.setObjectName('settab_slider_slider') self._slider.setOrientation(Qt.Horizontal) self._slider.setMaximumWidth(50) self._slider.setMinimum(0) self._slider.setMaximum(1) self._slider.valueChanged.connect(self.slider_moved) # add widgets to the slider sub layout self._widget_slider_layout.addWidget(self._label_left_slider, 0, 0, 1, 1) self._widget_slider_layout.addWidget(self._label_right_slider, 0, 2, 1, 1) self._widget_slider_layout.addWidget(self._slider, 0, 1, 1, 1) # button to write the config button self._button_write_config = QPushButton(self) self._button_write_config.setObjectName('settab_button_write_config') self._button_write_config.setText(self._tran.get_text(self._button_write_config.objectName())) self._button_write_config.clicked.connect(self._ui.write_config) # the horizontal line in the settings tab self._hline = QFrame(self) self._hline.setFrameShape(QFrame.HLine) self._hline.setFrameShadow(QFrame.Sunken) self._hline.setObjectName('settab_hline') # the show advanced settings tab checkbox self._checkbox_advset = QCheckBox(self) self._checkbox_advset.setObjectName('settab_checkbox_advanced_settings') self._checkbox_advset.setText(self._tran.get_text(self._checkbox_advset.objectName())) self._checkbox_advset.stateChanged.connect(self._toggle_advset_tab) # the display verbose tooltips checkbox self._checkbox_vertoo = QCheckBox(self) self._checkbox_vertoo.setObjectName('settab_checkbox_verbose_tooltips') self._checkbox_vertoo.setText(self._tran.get_text(self._checkbox_vertoo.objectName())) self._checkbox_vertoo.stateChanged.connect(lambda: self.toggle_tooltips(None)) # add the elements to the main layout self._layout.addWidget(self._label_clear, 0, 0, 1, 1) self._layout.addWidget(self._input_clear, 0, 1, 1, 1) self._layout.addWidget(self._button_clear, 0, 2, 1, 1) self._layout.addWidget(self._label_enc, 1, 0, 1, 1) self._layout.addWidget(self._input_enc, 1, 1, 1, 1) self._layout.addWidget(self._button_enc, 1, 2, 1, 1) self._layout.addWidget(self._label_key1, 2, 0, 1, 1) self._layout.addWidget(self._input_key1, 2, 1, 1, 1) self._layout.addWidget(self._button_key1, 2, 2, 1, 1) self._layout.addWidget(self._label_key2, 3, 0, 1, 1) self._layout.addWidget(self._input_key2, 3, 1, 1, 1) self._layout.addWidget(self._button_key2, 3, 2, 1, 1) self._layout.addWidget(self._hline, 4, 0, 1, 3) self._layout.addWidget(self._checkbox_advset, 5, 0, 1, 1) self._layout.addWidget(self._checkbox_vertoo, 5, 2, 1, 1) self._layout.addWidget(self._widget_slider, 6, 2, 1, 1, Qt.AlignHCenter | Qt.AlignVCenter) self._layout.addWidget(self._button_write_config, 6, 0, 1, 1) self._tooltips = [ self._label_clear, self._input_clear, self._button_clear, self._label_enc, self._input_enc, self._button_enc, self._label_key1, self._input_key1, self._button_key1, self._label_key2, self._input_key2, self._button_key2, self._checkbox_advset, self._checkbox_vertoo ] def _browse_clear_dir(self): """ Open a directory browser to select the directory for the plaintexts and set the text of the corresponding QLineEdit :return: None """ # the file browser will only allow choosing directories _opt = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly # open the file browser _dir = QFileDialog.getExistingDirectory(None, self._tran.get_text('settab_button_clear_desc'), self._input_clear.text(), _opt) if _dir: self._input_clear.setText(str(_dir)) def _browse_enc_dir(self): """ Open a directory browser to select the directory for the ciphertexts and set the text of the corresponding QLineEdit :return: None """ # the file browser will only allow choosing directories _opt = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly # open the file browser _dir = QFileDialog.getExistingDirectory(None, self._tran.get_text('settab_button_enc_desc'), self._input_enc.text(), _opt) if _dir: self._input_enc.setText(str(_dir)) def _verify_passwords(self): """ Check if the passwords the user entered are equal and satisfy the security requirements for passwords. :return: True if the passwords are valid; False if they are not """ if self._check_password_equality() and self._check_security_policy(): # the passwords are valid, so we can insert it into the config self._config[cc_con.USER_PW] = self._input_key1.text() return True else: return False def _check_security_policy(self): """ Check if the passwords the user entered meet the CloudCrypt security requirements for passwords :return: True if the password is sufficient and False if it isn't """ _length1 = len(str(self._input_key1.text())) _length2 = len(str(self._input_key2.text())) _ret = True # check if the first password is long enough if not (cc_con.PASSWORD_MIN_LEN <= _length1 <= cc_con.PASSWORD_MAX_LEN): # password is not long enough, so mark it as invalid self._mark_invalid(self._input_key1) self._mark_invalid(self._input_key2) # output error message self._ui.add_message(self._tran.get_text('password_1_policy_violation')) _ret = False else: # password is long enough, so remove messages claiming otherwise self._ui.del_message(self._tran.get_text('password_1_policy_violation')) # check if the second passsword is long enough if not (cc_con.PASSWORD_MIN_LEN <= _length2 <= cc_con.PASSWORD_MAX_LEN): # password not long enough, so mark it as invalid self._mark_invalid(self._input_key1) self._mark_invalid(self._input_key2) # output error message self._ui.add_message(self._tran.get_text('password_2_policy_violation')) _ret = False else: # password is long enough, so remove messages claiming otherwise self._ui.del_message(self._tran.get_text('password_2_policy_violation')) # both passwords are sufficient return _ret def _check_password_equality(self): """ Check if the two passwords the user provided are equal and mark the input fields accordingly :return: True if the passwords are equal and False if they are not """ _ret = True # check if they are equal if self._input_key1.text() != self._input_key2.text(): # passwords not equal -> mark input fields and output message self._mark_invalid(self._input_key1) self._mark_invalid(self._input_key2) # output error message self._ui.add_message(self._tran.get_text('passwords_not_equal')) _ret = False else: # passwords equal -> mark input fields and remove passwords not equal message self._mark_valid(self._input_key1) self._mark_valid(self._input_key2) # output error message self._ui.del_message(self._tran.get_text('passwords_not_equal')) _ret = True if _ret and self._input_key1.text() == base64.b64decode(b'Sm9zaHVh').decode('utf-8'): self._ui.helper.open_help('test.html', '') # passwords are equal return _ret @staticmethod def _mark_invalid(field): """ Mark a invalid input field :param field: the field that shall be marked as invalid :return: None """ try: field.setStyleSheet("QLineEdit{background: red;}") except AttributeError: pass # TODO error handling @staticmethod def _mark_valid(field): """ Mark a valid input field :param field: the field that shall be marked as valid :return: None """ try: field.setStyleSheet("QLineEdit{background: green;}") except AttributeError: pass # TODO error handling def _toggle_advset_tab(self): """ Show or hide the advanced settings tab :return: None """ if not self._checkbox_advset.isChecked(): self._ui.show_adv_tab(False) self._config[cc_con.SHOW_ADV_SET] = "False" else: self._ui.show_adv_tab(True) self._config[cc_con.SHOW_ADV_SET] = "True" def is_running(self): """ Whether the synchronisation between the two directories is currently running :return: True, if the synchronisation is running and False if it is not """ return self._running def tooltip_state(self): """ Whether the tooltips are turned on or off; True indicates on and False indicates off :return: True if the tooltips are on and False if they are off """ if cc_con.SHOW_VERB_TOOL in self._config: return self._str_to_bool(self._config[cc_con.SHOW_VERB_TOOL]) else: return True def lock(self): """ Disable the ui components, so that the user cannot change settings while the program is running :return: None """ self._toggle_ui_components(False) def unlock(self): """ Enable the ui components, so that the user can change settings :return: None """ self._toggle_ui_components(True) def _toggle_ui_components(self, onoff): """ Enable/Disable ui components (DO NOT USE THIS DIRECTLY; use _lock()/_unlock()) :param onoff: True to enable, False to disable :return: None """ self._button_clear.setEnabled(onoff) self._button_enc.setEnabled(onoff) self._button_key1.setEnabled(onoff) self._button_key2.setEnabled(onoff) self._checkbox_advset.setEnabled(onoff) self._checkbox_vertoo.setEnabled(onoff) self._button_write_config.setEnabled(onoff) def slider_moved(self, val=None): """ What to do, when the slider has been moved: check input fields and if the input is valid start the synchronisation between the two directories :param val: :return: """ # user specified an new value for the slider if val and val == "off" or val == "Off": _value = 0 elif val and val == "On" or val == "on": _value = 1 # user did not specify a new value for the slider else: _value = self._slider.value() # stop synchronisation between the two directories if _value == 0: self._ui.core_ref.stop_sync() # unset the flag indicating that the synchronisation is running self._running = False # allow the user to modify settings again, now that the synchronisation has stopped self.unlock() # check if all the input needed to start the synchronisation is valid elif _value == 1: if self._input_clear is None or self._input_enc is None: self.ui.add_message("Geben sie für beide Ordner eine Pfad an") self._slider.setValue("Off") return if not self._verify_passwords(): self._slider.setValue("Off") return # check if the passwords satisfy the security policy for passwords if not self._check_security_policy(): self._settab_slider_slider.setValue("Off") return # check if the password is correct _user_pass = str(self._input_key1.text()) if not self._ui.core_ref.is_password_correct(_user_pass): # password wrong self._ui.add_message(self._tran.get_text('password_not_correct')) self._slider.setValue("Off") return # password correct -> delete messages claiming otherwise from the message area elif self._tran.get_text('password_not_correct') in self._ui.messages: self._ui.del_messages(self._tran.get_text('password_not_correct')) # check if the directory paths are good _source = str(self._input_clear.text()) _cloud = str(self._input_enc.text()) if not os.path.exists(_source): # source directory path not good -> add message to message area self._ui.add_message(self._tran.get_text('source_folder_not_exist')) self._slider.setValue("Off") return # source path correct -> delete message claiming otherwise from the message area elif self._tran.get_text('source_folder_not_exist') in self._ui.messages: self._ui.del_messages(self._tran.get_text('source_folder_not_exist')) if not os.path.exists(_cloud): # cloud directory path not good -> add message to message area self._ui.add_message(self._tran.get_text('cloud_folder_not_exist')) self._ui.slider.setValue("Off") return # cloud path correct -> delete message claiming otherwise from the message area elif self._tran.get_text('cloud_folder_not_exist') in self._ui.messages: self._ui.del_messages(self._tran.get_text('cloud_folder_not_exist')) # all checks where successful -> start synchronisation self._thread = SyncThread(self._ui.core_ref, _source, _cloud, _user_pass) self._thread.start() # lock the ui, so that the user cannot change settings while the synchronisation is running self.lock() # set the flag indicating that the synchronisation is running self._running = True @staticmethod def _toggle_password(field): """ Display passwords in a QLineEdit in clear text and display clear text in a QLineEdit as password :param field: The field for which the echo mode shall be switched :return: None """ try: if field.echoMode() == QLineEdit.Password: field.setEchoMode(QLineEdit.Normal) else: field.setEchoMode(QLineEdit.Password) except AttributeError: # TODO error handling pass @staticmethod def _str_to_bool(string): """ Convert a string to boolean: "True" and "true" become True, everything else becomes False :param string: The string that shall be converted :return: True if the string was "True" or "true" and False if the string is something else """ if string == "True" or string == "true": return True else: return False def toggle_tooltips(self, onoff=""): """ Turn tool tips for this tab on or off :param onoff: "True" or "true" to turn tooltips on, False (actually everything but "True" and "true") to turn tooltips off if onoff is not set, then this method just toggles the tooltips :return: None """ # update config self._config[cc_con.SHOW_VERB_TOOL] = str(self._checkbox_vertoo.isChecked()) if onoff: # user specified whether he wants to turn tooltips on or off if onoff == "True" or onoff == "true": # turn on for ele in self._tooltips: ele.setToolTip(self._tran.get_text(ele.objectName() + cc_con.TOOLTIP_POSTFIX)) else: # turn off for ele in self._tooltips: ele.setToolTip("") else: # user did not specify whether he wants to turn tooltips on or off if cc_con.SHOW_VERB_TOOL in self._config and self._config[cc_con.SHOW_VERB_TOOL] == "True": self.toggle_tooltips("True") elif cc_con.SHOW_VERB_TOOL in self._config: self.toggle_tooltips("False") def init(self): """ What to do, when this tab is activated: fill the table with the contents of the config, ... :return: None """ # plaintext directory input field if cc_con.SCR_DIR in self._config: self._input_clear.setText(self._config[cc_con.SCR_DIR]) else: self._input_clear.setText(cc_con.SCR_DIR_DEFAULT) # encrypted directory input field if cc_con.DST_DIR in self._config: self._input_enc.setText(self._config[cc_con.DST_DIR]) else: self._input_enc.setText(cc_con.DST_DIR_DEFAULT) # the two password input fields if cc_con.USER_PW in self._config: self._input_key1.setText(self._config[cc_con.USER_PW]) self._input_key2.setText(self._config[cc_con.USER_PW]) else: self._input_key1.setText(cc_con.USER_PW_DEFAULT) self._input_key2.setText(cc_con.USER_PW_DEFAULT) # show advanced tab checkbox if cc_con.SHOW_ADV_SET in self._config: self._checkbox_advset.setChecked(self._str_to_bool(self._config[cc_con.SHOW_ADV_SET])) else: self._checkbox_advset.setChecked(self._str_to_bool(cc_con.SHOW_ADV_SET_DEFAULT)) # show verbose tooltips checkbox if cc_con.SHOW_VERB_TOOL in self._config: self._checkbox_vertoo.setChecked(self._str_to_bool(self._config[cc_con.SHOW_VERB_TOOL])) else: self._checkbox_vertoo.setChecked(self._str_to_bool(cc_con.SHOW_VERB_TOOL_DEFAULT)) def config(self): """ Return the internal configuration of this tab :return: A dictionary containing the configuration """ return self._config
def init_ui(self): try: self.setFont(QFont('Segoe UI')) headerLabel = QLabel('Survey name: ', self) analyses = [ 'Guildline Salinity', 'Scripps Oxygen', 'Seal Nutrients', 'Seasave CTD' ] analyseskey = ['guildline', 'scripps', 'seal', 'seasave'] with open(self.currpath + '/' + '%sParams.json' % self.currproject, 'r') as file: params = json.loads(file.read()) self.tabs = QTabWidget() self.salt_active = False self.oxy_active = False self.nuts_active = False self.ctdactive = False tabnotadded = True for i, analysis in enumerate(params['analysisparams'].keys()): print(analysis) if params['analysisparams'][analysis][ 'activated'] == True or self.survey == 'new': if analysis == 'seal': self.nutrient_tab = QWidget() self.tabs.addTab(self.nutrient_tab, 'Nutrients') self.nuts_active = True if analysis == 'guildline': self.salttab = QWidget() self.tabs.addTab(self.salttab, 'Salinity') self.salt_active = True if analysis == 'scripps': self.oxygentab = QWidget() self.tabs.addTab(self.oxygentab, 'Oxygen') self.oxy_active = True if analysis == 'seasave' and self.survey != 'new': self.ctdtab = QWidget() self.tabs.addTab(self.ctdtab, 'CTD') self.ctdactive = True tabnotadded = False if tabnotadded: self.add_analysis = QWidget() self.tabs.addTab(self.add_analysis, 'Tab') self.add_analysis_label = QLabel( 'Add an analysis first to set survey settings') self.add_analysis.layout = QGridLayout() self.add_analysis.layout.addWidget(self.add_analysis_label, 0, 0) self.add_analysis.setLayout(self.add_analysis.layout) save = QPushButton('Save', self) save.setMinimumWidth(100) save.clicked.connect(self.savefunction) cancel = QPushButton('Cancel', self) cancel.setMinimumWidth(100) cancel.clicked.connect(self.cancelfunction) self.grid_layout.addWidget(headerLabel, 0, 0) self.grid_layout.addWidget(self.surveyName, 0, 1) self.grid_layout.addWidget(self.tabs, 1, 0, 5, 3) self.grid_layout.addWidget(save, 10, 0) self.grid_layout.addWidget(cancel, 10, 2) self.setLayout(self.grid_layout) # Salinity Tab if self.salt_active: salt_grid = QGridLayout() salt_grid.setSpacing(5) self.activate_salt = QCheckBox( 'Activate for use with this survey', self) self.activate_salt.setStyleSheet( 'QCheckBox { font-weight: bold; }') self.ctd_survey_salt = QCheckBox( 'This is the survey for CTD samples ') self.ctd_survey_salt_label = QLabel( '<i>This is used for samples collected from a CTD and recorded ' 'with a logsheet. Tick if this is the CTD survey. \n</i>') self.ctd_survey_salt_label.setWordWrap(True) self.decode_salt = QCheckBox( 'Decode Salinity file Sample ID value to a survey') self.decode_salt_label = QLabel( '<i>Use this to represent a custom survey, such as underway or TSG. ' 'Keep the prefix short for ease of use. </i>') self.decode_salt_label.setWordWrap(True) # self.decodeOxygen.clicked.connect(self.enabledisable) self.survey_number_station_label = QLabel( 'Survey prefix on sample ID: ') self.survey_number_station = QLineEdit(self) self.decode_salt_deployment = QCheckBox( 'Decode deployment and RP from oxygen file') self.decode_salt_deployment_label = QLabel( '<i>Use the Cast and Rosette Position data columns to decode ' 'a deployment and rp. Do not use for typical CTD ' 'deployments, use for TMR or Coastal projects without a ' 'CTD file or logsheet.</i>') self.decode_salt_deployment_label.setWordWrap(True) dep_rp_format_salt_label = QLabel( 'Dep/Bottle format after prefix:') self.dep_rp_format_salt = QLineEdit() self.dep_rp_format_salt.setPlaceholderText('e.g. DDDBB') self.sample_salt_id = QCheckBox('Just use Sample ID', self) self.sample_salt_id_label = QLabel( '<i>Directly use sample ID instead of dep/ros label decoding system,' ' beware this overrides all other decoding of IDs') self.sample_salt_id_label.setWordWrap(True) saltlinesep1 = QFrame(self) saltlinesep1.setFrameShape(QFrame.HLine) saltlinesep1.setFrameShadow(QFrame.Sunken) salt_group_box = QGroupBox(self) salt_group_box.setTitle( ' Settings for grouping custom surveys ') salt_group_box.setStyleSheet("font-weight: bold;") salt_group_box.setAlignment(Qt.AlignRight) saltlinesep3 = QFrame(self) saltlinesep3.setFrameShape(QFrame.HLine) saltlinesep3.setFrameShadow(QFrame.Sunken) salt_grid.addWidget(self.activate_salt, 0, 1, 1, 4) salt_grid.addWidget(saltlinesep1, 1, 0, 1, 6) salt_grid.addWidget(self.ctd_survey_salt, 2, 1) salt_grid.addWidget(self.ctd_survey_salt_label, 3, 1, 1, 4) salt_grid.addWidget(salt_group_box, 4, 0, 10, 6) salt_grid.addWidget(self.decode_salt, 6, 1, 1, 4) salt_grid.addWidget(self.decode_salt_label, 7, 1, 1, 2) salt_grid.addWidget(self.survey_number_station_label, 8, 1, 1, 4) salt_grid.addWidget(self.survey_number_station, 8, 3) salt_grid.addWidget(saltlinesep3, 9, 1, 1, 4) salt_grid.addWidget(self.decode_salt_deployment, 10, 1, 1, 4) salt_grid.addWidget(self.decode_salt_deployment_label, 11, 1, 1, 4) salt_grid.addWidget(dep_rp_format_salt_label, 12, 1, 1, 2) salt_grid.addWidget(self.dep_rp_format_salt, 12, 3, 1, 1) salt_grid.addWidget(self.sample_salt_id, 14, 1) salt_grid.addWidget(self.sample_salt_id_label, 15, 1, 1, 6) self.salttab.setLayout(salt_grid) # Oxygen Tab if self.oxy_active: oxy_grid = QGridLayout() oxy_grid.setSpacing(5) self.activate_oxygen = QCheckBox( 'Activate for use with this survey', self) self.activate_oxygen.setStyleSheet( 'QCheckBox { font-weight: bold; }') self.ctd_survey_oxygen = QCheckBox( 'This is the survey for CTD samples ') self.ctd_survey_oxygen_label = QLabel( '<i>This is used for samples collected from a CTD and recorded ' 'with a logsheet. Tick if this is the CTD survey. \n</i>') self.ctd_survey_oxygen_label.setWordWrap(True) self.decode_oxygen = QCheckBox( 'Decode Oxygen file Station value to a survey') self.decode_oxygen_label = QLabel( '<i>Use this to represent a custom survey, do not use a station ' 'number less than 900. Less than 900 and HyPro will not recognise. Increase RP for each sample. </i>' ) self.decode_oxygen_label.setWordWrap(True) #self.decodeOxygen.clicked.connect(self.enabledisable) self.survey_number_station_label = QLabel( 'Enter a number to represent the survey: ') self.survey_number_station = QLineEdit(self) self.survey_number_station.setPlaceholderText('e.g. 901') self.decode_oxygen_deployment = QCheckBox( 'Decode deployment and RP from oxygen file') self.decode_oxygen_deployment_label = QLabel( '<i>Use the Cast and Rosette Position data columns to decode ' 'a deployment and rp. Do not use for typical CTD ' 'deployments, use for TMR or Coastal projects without a ' 'CTD file or logsheet.</i>') self.decode_oxygen_deployment_label.setWordWrap(True) self.sample_oxygen_id = QCheckBox('Just use Bottle ID', self) self.sample_oxygen_id_label = QLabel( '<i>Directly use bottle ID instead of dep/ros label decoding system,' ' beware this overrides all other decoding of IDs') self.sample_oxygen_id_label.setWordWrap(True) oxylinesep1 = QFrame(self) oxylinesep1.setFrameShape(QFrame.HLine) oxylinesep1.setFrameShadow(QFrame.Sunken) oxy_group_box = QGroupBox(self) oxy_group_box.setTitle( ' Settings for grouping custom surveys ') oxy_group_box.setStyleSheet("font-weight: bold;") oxy_group_box.setAlignment(Qt.AlignRight) oxylinesep3 = QFrame(self) oxylinesep3.setFrameShape(QFrame.HLine) oxylinesep3.setFrameShadow(QFrame.Sunken) oxy_grid.addWidget(self.activate_oxygen, 0, 1, 1, 4) oxy_grid.addWidget(oxylinesep1, 1, 1, 1, 6) oxy_grid.addWidget(self.ctd_survey_oxygen, 2, 1, 1, 1) oxy_grid.addWidget(self.ctd_survey_oxygen_label, 3, 1, 1, 4) oxy_grid.addWidget(oxy_group_box, 4, 0, 9, 6) oxy_grid.addWidget(self.decode_oxygen, 6, 1) oxy_grid.addWidget(self.decode_oxygen_label, 7, 1, 1, 4) oxy_grid.addWidget(self.survey_number_station_label, 8, 1, 1, 2) oxy_grid.addWidget(self.survey_number_station, 8, 3) oxy_grid.addWidget(oxylinesep3, 9, 1, 1, 4) oxy_grid.addWidget(self.decode_oxygen_deployment, 10, 1) oxy_grid.addWidget(self.decode_oxygen_deployment_label, 11, 1, 1, 4) oxy_grid.addWidget(self.sample_oxygen_id, 13, 1) oxy_grid.addWidget(self.sample_oxygen_id_label, 14, 1, 1, 6) self.oxygentab.setLayout(oxy_grid) # Nutrient tab if self.nuts_active: self.nutrient_tab.layout = QGridLayout() self.nutrient_tab.layout.setSpacing(5) self.activate_nutrient = QCheckBox( 'Activate for use with this survey', self) self.activate_nutrient.setStyleSheet( 'QCheckBox { font-weight: bold; }') #self.activateNutrient.clicked.connect(self.enabledisable) nut_linesep1 = QFrame() nut_linesep1.setFrameShape(QFrame.HLine) nut_linesep1.setFrameShadow(QFrame.Sunken) self.ctd_survey_nutrient = QCheckBox( 'This is the survey for CTD samples', self) ctd_survey_nutrient_label = QLabel( '<i>This is used for samples collected from a CTD and recorded ' 'with a logsheet. Tick if this is the CTD survey. Assumes sample' ' ID has Dep/RP format of DDBB.</i>') ctd_survey_nutrient_label.setWordWrap(True) nut_group_box = QGroupBox(self) nut_group_box.setTitle( ' Settings for grouping custom surveys ') nut_group_box.setStyleSheet("font-weight: bold;") nut_group_box.setAlignment(Qt.AlignRight) self.decode_nutrient = QCheckBox( 'Decode Sample ID value to a survey') decode_nutrient_label = QLabel( '<i>Use this to represent a custom survey, such as underway or TSG. Keep' ' the prefix short for ease of use.') decode_nutrient_label.setWordWrap(True) survey_prefix_nutrient_label = QLabel( 'Survey prefix on sample ID:') self.survey_prefix_nutrient = QLineEdit(self) self.survey_prefix_nutrient.setDisabled(True) nut_linesep2 = QFrame() nut_linesep2.setFrameShape(QFrame.HLine) nut_linesep2.setFrameShadow(QFrame.Sunken) self.decode_deployment_nutrient = QCheckBox( 'Decode deployment and RP from ID', self) decode_deprp_nutrient_label = QLabel( '<i>Decode the sample ID for deployment and RP. Do not use for ' 'typical CTD deployments, use for TMR or Coastal projects without' 'a CTD file or HyPro logsheet.</i>') decode_deprp_nutrient_label.setWordWrap(True) dep_rp_format_nutrient_label = QLabel( 'Dep/Bottle format after prefix:') self.dep_rp_format_nutrient = QLineEdit() self.dep_rp_format_nutrient.setPlaceholderText('e.g. DDDBB') self.sample_id_nutrient = QCheckBox('Just use sample ID', self) self.sample_id_nutrient.setToolTip( 'Please be aware this will supersede any other sample id matching.' ) sample_id_nutrient_label = QLabel( '<i>Use sample ID value instead of dep/rp label decoding' 'system, beware this overrides all other decoding of IDs') sample_id_nutrient_label.setWordWrap(True) self.nutrient_tab.layout.addWidget(self.activate_nutrient, 0, 1) self.nutrient_tab.layout.addWidget(nut_linesep1, 1, 0, 1, 6) self.nutrient_tab.layout.addWidget(self.ctd_survey_nutrient, 2, 1) self.nutrient_tab.layout.addWidget(ctd_survey_nutrient_label, 3, 1, 1, 4) self.nutrient_tab.layout.addWidget(nut_group_box, 4, 0, 9, 6) self.nutrient_tab.layout.addWidget(self.decode_nutrient, 5, 1, 1, 4) self.nutrient_tab.layout.addWidget(decode_nutrient_label, 6, 1, 1, 4) self.nutrient_tab.layout.addWidget( survey_prefix_nutrient_label, 7, 1, 1, 2) self.nutrient_tab.layout.addWidget(self.survey_prefix_nutrient, 7, 3) self.nutrient_tab.layout.addWidget(nut_linesep2, 8, 1, 1, 4) self.nutrient_tab.layout.addWidget( self.decode_deployment_nutrient, 9, 1, 1, 4) self.nutrient_tab.layout.addWidget(decode_deprp_nutrient_label, 10, 1, 1, 4) self.nutrient_tab.layout.addWidget( dep_rp_format_nutrient_label, 11, 1, 1, 2) self.nutrient_tab.layout.addWidget(self.dep_rp_format_nutrient, 11, 3, 1, 1) self.nutrient_tab.layout.addWidget(self.sample_id_nutrient, 13, 1) self.nutrient_tab.layout.addWidget(sample_id_nutrient_label, 14, 1, 1, 6) self.nutrient_tab.setLayout(self.nutrient_tab.layout) self.populatefields() except Exception: traceback.print_exc()
def __init__(self, *args): super().__init__(BrickletLCD16x2, *args) self.lcd = self.device # the firmware version of a EEPROM Bricklet can (under common circumstances) # not change during the lifetime of an EEPROM Bricklet plugin. therefore, # it's okay to make final decisions based on it here self.has_custom_character = self.firmware_version >= (2, 0, 1) self.qtcb_pressed.connect(self.cb_pressed) self.lcd.register_callback(self.lcd.CALLBACK_BUTTON_PRESSED, self.qtcb_pressed.emit) self.qtcb_released.connect(self.cb_released) self.lcd.register_callback(self.lcd.CALLBACK_BUTTON_RELEASED, self.qtcb_released.emit) self.line_label = QLabel('Line:') self.line_combo = QComboBox() for i in range(LCD16x2.MAX_LINE): self.line_combo.addItem(str(i)) self.pos_label = QLabel('Position:') self.pos_combo = QComboBox() for i in range(LCD16x2.MAX_POSITION): self.pos_combo.addItem(str(i)) self.line_pos_layout = QHBoxLayout() self.line_pos_layout.addWidget(self.line_label) self.line_pos_layout.addWidget(self.line_combo) self.line_pos_layout.addWidget(self.pos_label) self.line_pos_layout.addWidget(self.pos_combo) self.line_pos_layout.addStretch() self.text_label = QLabel('Text:') self.text_edit = QLineEdit() self.text_edit.setMaxLength(LCD16x2.MAX_POSITION) self.text_button = QPushButton('Send Text') self.text_layout = QHBoxLayout() self.text_layout.addWidget(self.text_label) self.text_layout.addWidget(self.text_edit) self.text_layout.addWidget(self.text_button) self.clear_button = QPushButton("Clear Display") self.bl_button = QPushButton() self.cursor_button = QPushButton() self.blink_button = QPushButton() self.onofflayout = QHBoxLayout() self.onofflayout.addWidget(self.bl_button) self.onofflayout.addWidget(self.cursor_button) self.onofflayout.addWidget(self.blink_button) self.b0_label = QLabel('Button 0: Released,') self.b1_label = QLabel('Button 1: Released,') self.b2_label = QLabel('Button 2: Released') self.buttonlayout = QHBoxLayout() self.buttonlayout.addWidget(self.b0_label) self.buttonlayout.addWidget(self.b1_label) self.buttonlayout.addWidget(self.b2_label) self.cursor_button.clicked.connect(self.cursor_clicked) self.blink_button.clicked.connect(self.blink_clicked) self.clear_button.clicked.connect(self.clear_clicked) self.bl_button.clicked.connect(self.bl_clicked) self.text_button.clicked.connect(self.text_clicked) if self.has_custom_character: line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.scribble_widget = ScribbleWidget(5, 8, 25, QColor(Qt.white), QColor(Qt.blue)) self.char_index_label = QLabel('Index:') self.char_index_combo = QComboBox() self.char_index_combo.currentIndexChanged.connect(self.char_index_changed) for i in range(8): self.char_index_combo.addItem(str(i)) self.char_index_layout = QHBoxLayout() self.char_index_layout.addStretch() self.char_index_layout.addWidget(self.char_index_label) self.char_index_layout.addWidget(self.char_index_combo) self.char_index_layout.addStretch() self.char_index_save = QPushButton('Save Character') self.char_index_save.clicked.connect(self.char_index_save_clicked) self.char_show = QPushButton('Show all Custom Characters on LCD') self.char_show.clicked.connect(self.show_clicked) self.char_save_layout = QVBoxLayout() self.char_save_layout.addStretch() self.char_save_layout.addLayout(self.char_index_layout) self.char_save_layout.addWidget(self.char_index_save) self.char_save_layout.addWidget(self.char_show) help_label = QLabel('Use "\\0, \\1, ..., \\7" in text field to show custom characters.') help_label.setWordWrap(True) self.char_save_layout.addWidget(help_label) self.char_save_layout.addStretch() grid_stretch_layout = QHBoxLayout() grid_stretch_layout.addWidget(QLabel('Custom Character:')) grid_stretch_layout.addWidget(self.scribble_widget) grid_stretch_layout.addLayout(self.char_save_layout) grid_stretch_layout.addStretch() self.char_main_layout = QHBoxLayout() self.char_main_layout.addStretch() self.char_main_layout.addLayout(grid_stretch_layout) self.char_main_layout.addStretch() layout = QVBoxLayout(self) layout.addLayout(self.line_pos_layout) layout.addLayout(self.text_layout) layout.addWidget(self.clear_button) layout.addLayout(self.onofflayout) layout.addLayout(self.buttonlayout) if self.has_custom_character: layout.addWidget(line) layout.addLayout(self.char_main_layout) layout.addStretch(1)
def __init__(self, *args): super().__init__(BrickletAmbientLightV3, *args) self.al = self.device self.cbe_illuminance = CallbackEmulator(self.al.get_illuminance, None, self.cb_illuminance, self.increase_error_count) self.alf = AmbientLightFrame() self.out_of_range_label = QLabel('Illuminance is out-of-range') self.saturated_label = QLabel('Sensor is saturated') self.out_of_range_label.hide() self.out_of_range_label.setStyleSheet('QLabel { color: red }') self.saturated_label.hide() self.saturated_label.setStyleSheet('QLabel { color: magenta }') self.current_illuminance = CurveValueWrapper() # float, lx plots = [('Illuminance', Qt.red, self.current_illuminance, '{:.2f} lx (Lux)'.format)] self.plot_widget = PlotWidget('Illuminance [lx]', plots, extra_key_widgets=[self.out_of_range_label, self.saturated_label, self.alf], y_resolution=0.001) self.range_label = QLabel('Illuminance Range:') self.range_combo = QComboBox() self.range_combo.addItem("Unlimited", BrickletAmbientLightV3.ILLUMINANCE_RANGE_UNLIMITED) self.range_combo.addItem("0 - 64000 lx", BrickletAmbientLightV3.ILLUMINANCE_RANGE_64000LUX) self.range_combo.addItem("0 - 32000 lx", BrickletAmbientLightV3.ILLUMINANCE_RANGE_32000LUX) self.range_combo.addItem("0 - 16000 lx", BrickletAmbientLightV3.ILLUMINANCE_RANGE_16000LUX) self.range_combo.addItem("0 - 8000 lx", BrickletAmbientLightV3.ILLUMINANCE_RANGE_8000LUX) self.range_combo.addItem("0 - 1300 lx", BrickletAmbientLightV3.ILLUMINANCE_RANGE_1300LUX) self.range_combo.addItem("0 - 600 lx", BrickletAmbientLightV3.ILLUMINANCE_RANGE_600LUX) self.range_combo.currentIndexChanged.connect(self.new_config) self.time_label = QLabel('Integration Time:') self.time_combo = QComboBox() self.time_combo.addItem("50 ms", BrickletAmbientLightV3.INTEGRATION_TIME_50MS) self.time_combo.addItem("100 ms", BrickletAmbientLightV3.INTEGRATION_TIME_100MS) self.time_combo.addItem("150 ms", BrickletAmbientLightV3.INTEGRATION_TIME_150MS) self.time_combo.addItem("200 ms", BrickletAmbientLightV3.INTEGRATION_TIME_200MS) self.time_combo.addItem("250 ms", BrickletAmbientLightV3.INTEGRATION_TIME_250MS) self.time_combo.addItem("300 ms", BrickletAmbientLightV3.INTEGRATION_TIME_300MS) self.time_combo.addItem("350 ms", BrickletAmbientLightV3.INTEGRATION_TIME_350MS) self.time_combo.addItem("400 ms", BrickletAmbientLightV3.INTEGRATION_TIME_400MS) self.time_combo.currentIndexChanged.connect(self.new_config) hlayout = QHBoxLayout() hlayout.addWidget(self.range_label) hlayout.addWidget(self.range_combo) hlayout.addStretch() hlayout.addWidget(self.time_label) hlayout.addWidget(self.time_combo) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
class Ui_StockAnalysisTool(QMainWindow): def __init__(self, relative_path_correction: str = ""): super(Ui_StockAnalysisTool, self).__init__() # TODO self.valid_stock_tickers = ["AMZN"] # Initialize Object Attributes self.source = list(Ui_StockAnalysisTool.StockSources)[0] self.sample_rates = [ sample_rate.value for sample_rate in Ui_StockAnalysisTool.SampleRates ] self.time_deltas = [ time_delta.value for time_delta in Ui_StockAnalysisTool.TimeDeltas ] self.stock = self.valid_stock_tickers[0] self.df = retrieve_yahoo_fin_stock_data(ticker=self.stock) self.first_date = self.df.index[0] self.last_date = self.df.index[-1] self.data_lines = {} self.indicators = {} self.colors = { 'blue': QColor(0, 0, 255, 255), 'cyan': QColor(0, 255, 255, 255), 'magenta': QColor(255, 0, 255, 255), 'yellow': QColor(255, 255, 0, 255), 'white': QColor(255, 255, 255, 255), 'dark-gray': QColor(125, 125, 125, 255), 'light-gray': QColor(200, 200, 200, 255), 'gray': QColor(100, 100, 150, 255), 'orange': QColor(255, 165, 0, 255), 'salmon': QColor(250, 128, 144, 255), 'violet': QColor(230, 130, 238, 255), 'aqua-marine': QColor(127, 255, 212, 255) } self.color_iterator = 0 self.protected_colors = { 'green': QColor(0, 255, 0, 255), 'red': QColor(255, 0, 0, 255) } self.robinhood_account_name = "" self.robinhood_account_password = "" self.rsi_n = 14 self.cmo_n = 7 self.macd_slow = 26 self.macd_fast = 12 self.macd_sign = 9 self.roc_n = 12 self.cci_n = 20 self.dpo_n = 20 self.cmf_n = 20 self.adx_n = 14 # Initialize UI Attributes. Then Initialize UI self.central_widget = None self.central_layout = None self.title_label = None self.title_h_divider = None self.display_layout = None self.graph_layout = None self.graph = None self.date_axis = None self.graph_legend = None self.data_selection_layout = None self.open_data_cb = None self.high_data_cb = None self.low_data_cb = None self.close_data_cb = None self.adjclose_data_cb = None self.volume_data_cb = None self.save_fig_btn = None self.graph_options_layout = None self.sample_rate_label = None self.sample_rate_combo = None self.time_delta_label = None self.time_delta_combo = None self.main_v_divider = None self.options_layout = None self.source_selection_layout = None self.source_label = None self.source_combo = None self.stock_selection_layout = None self.stock_label = None self.stock_combo = None self.robinhood_account_name_textedit = None self.robinhood_password_textedit = None self.robinhood_login_button = None self.top_h_divider = None self.second_from_top_h_divider = None self.momentum_indicator_label = None self.momentum_indicator_layout = None self.rsi_cb = None self.rsi_time_frame_label = None self.rsi_time_frame_text = None self.williams_r_cb = None self.cmo_cb = None self.macd_cb = None self.roc_cb = None self.middle_h_divider = None self.averages_label = None self.averages_layout = None self.wma_cb = None self.ema_cb = None self.sma_cb = None self.hma_cb = None self.trix_cb = None self.bottom_h_divider = None self.trend_indicators_label = None self.trend_indicators_layout = None self.cci_cb = None self.dpo_cb = None self.cmf_cb = None self.adx_cb = None self.force_index_cb = None self.statusbar = None self.setupUi() def setupUi(self) -> None: """ :return: """ # Generated Setup Code self.setObjectName("StockAnalysisTool_Ui") self.central_widget = QWidget(self) self.central_widget.setObjectName("central_widget") self.central_layout = QVBoxLayout(self.central_widget) self.central_layout.setObjectName("central_layout") self.title_label = QLabel(self.central_widget) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.title_label.sizePolicy().hasHeightForWidth()) self.title_label.setSizePolicy(sizePolicy) font = QFont() font.setFamily("Garamond") font.setPointSize(22) font.setBold(True) font.setWeight(75) self.title_label.setFont(font) self.title_label.setAlignment(Qt.AlignCenter) self.title_label.setObjectName("title_label") self.central_layout.addWidget(self.title_label) self.title_h_divider = QFrame(self.central_widget) self.title_h_divider.setFrameShape(QFrame.HLine) self.title_h_divider.setFrameShadow(QFrame.Sunken) self.title_h_divider.setObjectName("title_h_divider") self.central_layout.addWidget(self.title_h_divider) self.display_layout = QHBoxLayout() self.display_layout.setObjectName("display_layout") self.graph_layout = QVBoxLayout() self.graph_layout.setObjectName("graph_layout") self.date_axis = pg.DateAxisItem(orientation='bottom') self.graph = pg.PlotWidget(axisItems={'bottom': self.date_axis}) self.graph_legend = self.graph.addLegend() self.graph_layout.addWidget(self.graph) self.data_selection_layout = QGridLayout() self.open_data_cb = QCheckBox(self.central_widget) self.open_data_cb.setObjectName("open") self.data_selection_layout.addWidget(self.open_data_cb, 0, 0, 1, 1) self.high_data_cb = QCheckBox(self.central_widget) self.high_data_cb.setObjectName("high") self.data_selection_layout.addWidget(self.high_data_cb, 0, 1, 1, 1) self.low_data_cb = QCheckBox(self.central_widget) self.low_data_cb.setObjectName("low") self.data_selection_layout.addWidget(self.low_data_cb, 0, 2, 1, 1) self.close_data_cb = QCheckBox(self.central_widget) self.close_data_cb.setObjectName("close") self.data_selection_layout.addWidget(self.close_data_cb, 0, 3, 1, 1) self.adjclose_data_cb = QCheckBox(self.central_widget) self.adjclose_data_cb.setObjectName("adjclose") self.data_selection_layout.addWidget(self.adjclose_data_cb, 0, 4, 1, 1) self.volume_data_cb = QCheckBox(self.central_widget) self.volume_data_cb.setObjectName("volume") self.data_selection_layout.addWidget(self.volume_data_cb, 0, 5, 1, 1) self.graph_layout.addLayout(self.data_selection_layout) self.save_fig_btn = QPushButton(self.central_widget) self.save_fig_btn.setObjectName("save_fig_btn") self.graph_layout.addWidget(self.save_fig_btn) self.graph_options_layout = QGridLayout() self.sample_rate_label = QLabel(self.central_widget) self.sample_rate_label.setText("Sample Rate:") self.graph_options_layout.addWidget(self.sample_rate_label, 0, 0, 1, 1) self.sample_rate_combo = QComboBox(self.central_widget) self.sample_rate_combo.addItems(self.sample_rates) self.graph_options_layout.addWidget(self.sample_rate_combo, 0, 1, 1, 1) self.time_delta_label = QLabel(self.central_widget) self.time_delta_label.setText("Time delta:") self.graph_options_layout.addWidget(self.time_delta_label, 0, 2, 1, 1) self.time_delta_combo = QComboBox(self.central_widget) self.time_delta_combo.addItems(self.time_deltas) self.graph_options_layout.addWidget(self.time_delta_combo, 0, 3, 1, 1) self.graph_layout.addLayout(self.graph_options_layout) self.display_layout.addLayout(self.graph_layout) self.main_v_divider = QFrame(self.central_widget) self.main_v_divider.setFrameShape(QFrame.VLine) self.main_v_divider.setFrameShadow(QFrame.Sunken) self.main_v_divider.setObjectName("main_v_divider") self.display_layout.addWidget(self.main_v_divider) self.options_layout = QVBoxLayout() self.options_layout.setObjectName("options_layout") robinhood_account_layout = QHBoxLayout() robinhood_account_name_label = QLabel(self.central_widget) robinhood_account_name_label.setText("Robinhood Account:") self.robinhood_account_name_textedit = QTextEdit() robinhood_account_layout.addWidget(robinhood_account_name_label) robinhood_account_layout.addWidget( self.robinhood_account_name_textedit) self.options_layout.addLayout(robinhood_account_layout) robinhood_password_layout = QHBoxLayout() robinhood_account_password_label = QLabel(self.central_widget) robinhood_account_password_label.setText("Robinhood Password:"******"robinhood_login_button") self.options_layout.addWidget(self.robinhood_login_button) self.top_h_divider = QFrame(self.central_widget) self.top_h_divider.setFrameShape(QFrame.HLine) self.top_h_divider.setFrameShadow(QFrame.Sunken) self.top_h_divider.setObjectName("top_h_divider") self.options_layout.addWidget(self.top_h_divider) self.source_selection_layout = QHBoxLayout() self.source_selection_layout.setObjectName("source_selection_layout") self.source_label = QLabel(self.central_widget) self.source_label.setObjectName("source_label") self.source_selection_layout.addWidget(self.source_label) self.source_combo = QComboBox(self.central_widget) self.source_combo.setObjectName("source_combo") self.source_combo.addItem("") self.source_combo.addItem("") self.source_combo.addItem("") self.source_selection_layout.addWidget(self.source_combo) self.options_layout.addLayout(self.source_selection_layout) self.stock_selection_layout = QHBoxLayout() self.stock_selection_layout.setObjectName("stock_selection_layout") self.stock_label = QLabel(self.central_widget) self.stock_label.setObjectName("stock_label") self.stock_selection_layout.addWidget(self.stock_label) self.stock_combo = QComboBox(self.central_widget) self.stock_combo.setObjectName("stock_combo") self.stock_combo.addItems(self.valid_stock_tickers) self.stock_selection_layout.addWidget(self.stock_combo) self.options_layout.addLayout(self.stock_selection_layout) self.second_from_top_h_divider = QFrame(self.central_widget) self.second_from_top_h_divider.setFrameShape(QFrame.HLine) self.second_from_top_h_divider.setFrameShadow(QFrame.Sunken) self.second_from_top_h_divider.setObjectName( "second_from_top_h_divider") self.options_layout.addWidget(self.second_from_top_h_divider) self.momentum_indicator_label = QLabel(self.central_widget) self.momentum_indicator_label.setObjectName("momentum_indicator_label") self.options_layout.addWidget(self.momentum_indicator_label) # Momentum Indicators self.momentum_indicator_layout = QGridLayout() self.rsi_cb = QCheckBox(self.central_widget) self.rsi_cb.setObjectName("rsi_cb") self.momentum_indicator_layout.addWidget(self.rsi_cb, 0, 0, 1, 1) self.rsi_time_frame_label = QLabel(self.central_widget) self.rsi_time_frame_label.setText("Time frame:") self.momentum_indicator_layout.addWidget(self.rsi_time_frame_label, 0, 1, 1, 1) self.rsi_time_frame_text = QTextEdit(self.central_widget) font_metric = QFontMetrics(self.rsi_time_frame_text.font()) self.rsi_time_frame_text.setFixedHeight(font_metric.lineSpacing()) self.rsi_time_frame_text.setFixedWidth(50) self.rsi_time_frame_text.setText(str(self.rsi_n)) self.momentum_indicator_layout.addWidget(self.rsi_time_frame_text, 0, 2, 1, 1) self.williams_r_cb = QCheckBox(self.central_widget) self.williams_r_cb.setObjectName("williams_r_cb") self.momentum_indicator_layout.addWidget(self.williams_r_cb, 1, 0, 1, 1) self.cmo_cb = QCheckBox(self.central_widget) self.cmo_cb.setObjectName("cmo_cb") self.momentum_indicator_layout.addWidget(self.cmo_cb, 2, 0, 1, 1) self.macd_cb = QCheckBox(self.central_widget) self.macd_cb.setObjectName("macd_cb") self.momentum_indicator_layout.addWidget(self.macd_cb, 3, 0, 1, 1) self.roc_cb = QCheckBox(self.central_widget) self.roc_cb.setObjectName("roc_cb") self.momentum_indicator_layout.addWidget(self.roc_cb, 4, 0, 1, 1) self.middle_h_divider = QFrame(self.central_widget) self.middle_h_divider.setFrameShape(QFrame.HLine) self.middle_h_divider.setFrameShadow(QFrame.Sunken) self.middle_h_divider.setObjectName("middle_h_divider") self.options_layout.addLayout(self.momentum_indicator_layout) self.options_layout.addWidget(self.middle_h_divider) # Averages Indicators self.averages_label = QLabel(self.central_widget) self.averages_label.setObjectName("averages_label") self.options_layout.addWidget(self.averages_label) self.wma_cb = QCheckBox(self.central_widget) self.wma_cb.setObjectName("wma_cb") self.options_layout.addWidget(self.wma_cb) self.ema_cb = QCheckBox(self.central_widget) self.ema_cb.setObjectName("ema_cb") self.options_layout.addWidget(self.ema_cb) self.sma_cb = QCheckBox(self.central_widget) self.sma_cb.setObjectName("sma_cb") self.options_layout.addWidget(self.sma_cb) self.hma_cb = QCheckBox(self.central_widget) self.hma_cb.setObjectName("hma_cb") self.options_layout.addWidget(self.hma_cb) self.trix_cb = QCheckBox(self.central_widget) self.trix_cb.setObjectName("trix_cb") self.options_layout.addWidget(self.trix_cb) self.bottom_h_divider = QFrame(self.central_widget) self.bottom_h_divider.setFrameShape(QFrame.HLine) self.bottom_h_divider.setFrameShadow(QFrame.Sunken) self.bottom_h_divider.setObjectName("bottom_h_divider") self.options_layout.addWidget(self.bottom_h_divider) # Trend Indicators self.trend_indicators_label = QLabel(self.central_widget) self.trend_indicators_label.setObjectName("trend_indicators_label") self.options_layout.addWidget(self.trend_indicators_label) self.cci_cb = QCheckBox(self.central_widget) self.cci_cb.setObjectName("cci_cb") self.options_layout.addWidget(self.cci_cb) self.dpo_cb = QCheckBox(self.central_widget) self.dpo_cb.setObjectName("dpo_cb") self.options_layout.addWidget(self.dpo_cb) self.cmf_cb = QCheckBox(self.central_widget) self.cmf_cb.setObjectName("cmf_cb") self.options_layout.addWidget(self.cmf_cb) self.adx_cb = QCheckBox(self.central_widget) self.adx_cb.setObjectName("adx_cb") self.options_layout.addWidget(self.adx_cb) self.force_index_cb = QCheckBox(self.central_widget) self.force_index_cb.setObjectName("checkBox_14") self.options_layout.addWidget(self.force_index_cb) self.display_layout.addLayout(self.options_layout) self.central_layout.addLayout(self.display_layout) self.setCentralWidget(self.central_widget) self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) self.retranslateUi() self.setCallbacks() QMetaObject.connectSlotsByName(self) def setCallbacks(self) -> None: """ :return: """ self.sample_rate_combo.currentIndexChanged.connect( lambda: Ui_StockAnalysisTool.Callbacks.sample_rate_combo_changed( combo=self.sample_rate_combo)) self.time_delta_combo.currentIndexChanged.connect( lambda: Ui_StockAnalysisTool.Callbacks.time_delta_combo_changed( stock_analysis_tool=self, combo=self.time_delta_combo)) self.source_combo.currentIndexChanged.connect( lambda: Ui_StockAnalysisTool.Callbacks.source_combo_changed( combo=self.source_combo)) self.stock_combo.currentIndexChanged.connect( lambda: Ui_StockAnalysisTool.Callbacks.stock_combo_changed( stock_analysis_tool=self, combo=self.stock_combo, source=self.source)) self.open_data_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.open_data_cb_pressed( stock_analysis_tool=self, cb=self.open_data_cb)) self.high_data_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.high_data_cb_pressed( stock_analysis_tool=self, cb=self.high_data_cb)) self.low_data_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.low_data_cb_pressed( stock_analysis_tool=self, cb=self.low_data_cb)) self.close_data_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.close_data_cb_pressed( stock_analysis_tool=self, cb=self.close_data_cb)) self.adjclose_data_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.adjclose_data_cb_pressed( stock_analysis_tool=self, cb=self.adjclose_data_cb)) self.volume_data_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.volume_data_cb_pressed( stock_analysis_tool=self, cb=self.volume_data_cb)) self.robinhood_account_name_textedit.textChanged.connect( lambda: Ui_StockAnalysisTool.Callbacks. robinhood_account_name_text_changed( stock_analysis_tool=self, robinhood_account_name_textedit=self. robinhood_account_name_textedit)) self.robinhood_password_textedit.textChanged.connect( lambda: Ui_StockAnalysisTool.Callbacks. robinhood_password_text_changed(stock_analysis_tool=self, robinhood_password_textedit=self. robinhood_password_textedit)) self.robinhood_login_button.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.robinhood_login( robinhood_login_name=self.robinhood_account_name, robinhood_password=self.robinhood_account_password)) self.rsi_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.rsi_cb_pressed( stock_analysis_tool=self, cb=self.rsi_cb)) self.rsi_time_frame_text.textChanged.connect( lambda: Ui_StockAnalysisTool.Callbacks.rsi_time_frame_text_changed( stock_analysis_tool=self, rsi_time_frame_text=self.rsi_time_frame_text)) self.williams_r_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.williams_r_cb_pressed( stock_analysis_tool=self, cb=self.williams_r_cb)) self.cmo_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.cmo_cb_pressed( stock_analysis_tool=self, cb=self.cmo_cb)) self.macd_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.macd_cb_pressed( stock_analysis_tool=self, cb=self.macd_cb)) self.roc_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.roc_cb_pressed( stock_analysis_tool=self, cb=self.roc_cb)) self.wma_cb.clicked.connect(lambda: Ui_StockAnalysisTool.Callbacks. wma_cb_pressed(cb=self.wma_cb)) self.ema_cb.clicked.connect(lambda: Ui_StockAnalysisTool.Callbacks. ema_cb_pressed(cb=self.ema_cb)) self.sma_cb.clicked.connect(lambda: Ui_StockAnalysisTool.Callbacks. sma_cb_pressed(cb=self.sma_cb)) self.hma_cb.clicked.connect(lambda: Ui_StockAnalysisTool.Callbacks. hma_cb_pressed(cb=self.hma_cb)) self.trix_cb.clicked.connect(lambda: Ui_StockAnalysisTool.Callbacks. trix_cb_pressed(cb=self.trix_cb)) self.cci_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.cci_cb_pressed( stock_analysis_tool=self, cb=self.cci_cb)) self.dpo_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.dpo_cb_pressed( stock_analysis_tool=self, cb=self.dpo_cb)) self.cmf_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.cmf_cb_pressed( stock_analysis_tool=self, cb=self.cmf_cb)) self.adx_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.adx_cb_pressed( stock_analysis_tool=self, cb=self.adx_cb)) self.force_index_cb.clicked.connect( lambda: Ui_StockAnalysisTool.Callbacks.force_index_cb_pressed( cb=self.force_index_cb)) def retranslateUi(self) -> None: """ :return: """ _translate = QCoreApplication.translate self.setWindowTitle( _translate("StockAnalysisTool_Ui", "Stock Analysis Tool")) self.title_label.setText( _translate("StockAnalysisTool_Ui", "Robbin Stock Analysis Tool")) self.save_fig_btn.setText( _translate("StockAnalysisTool_Ui", "Export Graph")) self.source_label.setText(_translate("StockAnalysisTool_Ui", "Source:")) self.source_combo.setItemText( 0, _translate("StockAnalysisTool_Ui", "yahoo_fin")) self.source_combo.setItemText( 1, _translate("StockAnalysisTool_Ui", "ASTRASS")) self.source_combo.setItemText( 2, _translate("StockAnalysisTool_Ui", "yfinance")) self.stock_label.setText(_translate("StockAnalysisTool_Ui", "Stock:")) self.momentum_indicator_label.setText( _translate("StockAnalysisTool_Ui", "Momentum Indicators")) self.open_data_cb.setText(_translate("StockAnalysisTool_Ui", "open")) self.high_data_cb.setText(_translate("StockAnalysisTool_Ui", "high")) self.low_data_cb.setText(_translate("StockAnalysisTool_Ui", "low")) self.close_data_cb.setText(_translate("StockAnalysisTool_Ui", "close")) self.adjclose_data_cb.setText( _translate("StockAnalysisTool_Ui", "adjclose")) self.volume_data_cb.setText( _translate("StockAnalysisTool_Ui", "volume")) self.robinhood_login_button.setText( _translate("StockAnalysisTool_Ui", "Login")) self.rsi_cb.setText(_translate("StockAnalysisTool_Ui", "RSI")) self.williams_r_cb.setText( _translate("StockAnalysisTool_Ui", "WilliamsR")) self.cmo_cb.setText(_translate("StockAnalysisTool_Ui", "CMO")) self.macd_cb.setText(_translate("StockAnalysisTool_Ui", "MACD")) self.roc_cb.setText(_translate("StockAnalysisTool_Ui", "ROC")) self.averages_label.setText( _translate("StockAnalysisTool_Ui", "Averages")) self.wma_cb.setText(_translate("StockAnalysisTool_Ui", "WMA")) self.ema_cb.setText(_translate("StockAnalysisTool_Ui", "EMA")) self.sma_cb.setText(_translate("StockAnalysisTool_Ui", "SMA")) self.hma_cb.setText(_translate("StockAnalysisTool_Ui", "HMA")) self.trix_cb.setText(_translate("StockAnalysisTool_Ui", "TRIX")) self.trend_indicators_label.setText( _translate("StockAnalysisTool_Ui", "Trend Indicators")) self.cci_cb.setText(_translate("StockAnalysisTool_Ui", "CCI")) self.dpo_cb.setText(_translate("StockAnalysisTool_Ui", "DPO")) self.cmf_cb.setText(_translate("StockAnalysisTool_Ui", "CMF")) self.adx_cb.setText(_translate("StockAnalysisTool_Ui", "ADX")) self.force_index_cb.setText( _translate("StockAnalysisTool_Ui", "Force Index")) def add_column_to_graph(self, column_name: str, color: Union[QColor, None] = None) -> None: """ :param column_name: :param color: :return: """ relevant_df = self.get_relevant_data_frame() x = [datetime.timestamp(date_time) for date_time in relevant_df.index] if color is None: self.data_lines[column_name] = self.graph.plot( x=x, y=relevant_df[column_name], pen=pg.mkPen(color=self.colors[list(self.colors.keys())[ self.color_iterator]]), name=column_name) self.color_iterator += 1 self.color_iterator %= len(self.colors.keys()) else: self.data_lines[column_name] = self.graph.plot( x=x, y=relevant_df[column_name], pen=pg.mkPen(color=color), name=column_name) def remove_column_from_graph(self, column_name: str) -> None: """ :param column_name: :return: """ self.graph.removeItem(self.data_lines[column_name]) del self.data_lines[column_name] def update_data_on_graph(self, data_frame: DataFrame) -> None: """ :param data_frame: :return: """ x = [datetime.timestamp(date_time) for date_time in data_frame.index] for data_line_key, data_line in self.data_lines.items(): data_line.setData(x=x, y=data_frame[data_line_key]) def get_relevant_data_frame(self) -> DataFrame: """ :return: """ return self.df.truncate(before=self.first_date, after=self.last_date) class Callbacks: @staticmethod def generic_data_cb_pressed(stock_analysis_tool: QMainWindow, checked: bool, df_column_name: str) -> None: if checked: # Add open data to graph stock_analysis_tool.add_column_to_graph( column_name=df_column_name) else: # Remove open data from graph stock_analysis_tool.remove_column_from_graph( column_name=df_column_name) @staticmethod def source_combo_changed(combo: QComboBox) -> None: combo_text = combo.currentText() @staticmethod def stock_combo_changed(stock_analysis_tool: QMainWindow, combo: QComboBox, source: IntEnum) -> None: combo_text = combo.currentText() if source == Ui_StockAnalysisTool.StockSources.YAHOO_FIN: stock_analysis_tool.df = retrieve_yahoo_fin_stock_data( ticker=combo_text) elif source == Ui_StockAnalysisTool.StockSources.ASTRASS: # retrieve data from ASTRASS stock_analysis_tool.df = None elif source == Ui_StockAnalysisTool.StockSources.YFINANCE: # retrieve data from YFinance stock_analysis_tool.df = None stock_analysis_tool.update_data_on_graph( data_frame=stock_analysis_tool.df) @staticmethod def sample_rate_combo_changed(combo: QComboBox) -> None: combo_text = combo.currentText() @staticmethod def time_delta_combo_changed(stock_analysis_tool: QMainWindow, combo: QComboBox) -> None: """ :param stock_analysis_tool: :param combo: :return: """ new_time_delta = Ui_StockAnalysisTool.TimeDeltas( combo.currentText()) min_date = stock_analysis_tool.df.index[0].to_pydatetime() max_date = stock_analysis_tool.df.index[-1].to_pydatetime() if new_time_delta == Ui_StockAnalysisTool.TimeDeltas.FIVE_YEARS: min_date = max_date - timedelta(days=365 * 5) elif new_time_delta == Ui_StockAnalysisTool.TimeDeltas.ONE_YEAR: min_date = max_date - timedelta(days=365 * 1) elif new_time_delta == Ui_StockAnalysisTool.TimeDeltas.YEAR_TO_DATE: min_date = min_date.replace(year=max_date.year, month=1, day=1) elif new_time_delta == Ui_StockAnalysisTool.TimeDeltas.SIX_MONTHS: min_date = max_date - dateutil.relativedelta.relativedelta( months=6) elif new_time_delta == Ui_StockAnalysisTool.TimeDeltas.ONE_MONTH: min_date = max_date - dateutil.relativedelta.relativedelta( months=1) elif new_time_delta == Ui_StockAnalysisTool.TimeDeltas.FIVE_DAYS: min_date = max_date - timedelta(days=5) stock_analysis_tool.first_date = min_date stock_analysis_tool.last_date = max_date stock_analysis_tool.update_data_on_graph( stock_analysis_tool.get_relevant_data_frame()) @staticmethod def open_data_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: Ui_StockAnalysisTool.Callbacks.generic_data_cb_pressed( stock_analysis_tool=stock_analysis_tool, checked=cb.isChecked(), df_column_name='open') @staticmethod def high_data_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: Ui_StockAnalysisTool.Callbacks.generic_data_cb_pressed( stock_analysis_tool=stock_analysis_tool, checked=cb.isChecked(), df_column_name='high') @staticmethod def low_data_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: Ui_StockAnalysisTool.Callbacks.generic_data_cb_pressed( stock_analysis_tool=stock_analysis_tool, checked=cb.isChecked(), df_column_name='low') @staticmethod def close_data_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: Ui_StockAnalysisTool.Callbacks.generic_data_cb_pressed( stock_analysis_tool=stock_analysis_tool, checked=cb.isChecked(), df_column_name='close') @staticmethod def adjclose_data_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: Ui_StockAnalysisTool.Callbacks.generic_data_cb_pressed( stock_analysis_tool=stock_analysis_tool, checked=cb.isChecked(), df_column_name='adjclose') @staticmethod def volume_data_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: Ui_StockAnalysisTool.Callbacks.generic_data_cb_pressed( stock_analysis_tool=stock_analysis_tool, checked=cb.isChecked(), df_column_name='volume') @staticmethod def robinhood_account_name_text_changed( stock_analysis_tool: QMainWindow, robinhood_account_name_textedit: QTextEdit) -> None: text = robinhood_account_name_textedit.toPlainText() stock_analysis_tool.robinhood_account_name = text @staticmethod def robinhood_password_text_changed( stock_analysis_tool: QMainWindow, robinhood_password_textedit: QTextEdit) -> None: text = robinhood_password_textedit.toPlainText() stock_analysis_tool.robinhood_password = text @staticmethod def robinhood_login(robinhood_account_name: str, robinhood_password: str) -> None: pass @staticmethod def rsi_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: """ :param stock_analysis_tool: :param cb: :return: """ if cb.isChecked(): # Add RSI to Display Graph stock_analysis_tool.df['rsi'] = rsi( close=stock_analysis_tool.df['close'], n=stock_analysis_tool.rsi_n) stock_analysis_tool.df['rsi overbought'] = 70 stock_analysis_tool.df['rsi oversold'] = 30 stock_analysis_tool.add_column_to_graph(column_name='rsi') stock_analysis_tool.add_column_to_graph( column_name='rsi overbought', color=stock_analysis_tool.protected_colors['red']) stock_analysis_tool.add_column_to_graph( column_name='rsi oversold', color=stock_analysis_tool.protected_colors['green']) else: # Remove RSI from Display Graph stock_analysis_tool.remove_column_from_graph(column_name='rsi') stock_analysis_tool.remove_column_from_graph( column_name='rsi overbought') stock_analysis_tool.remove_column_from_graph( column_name='rsi oversold') stock_analysis_tool.df = stock_analysis_tool.df.drop("rsi", axis=1) stock_analysis_tool.df = stock_analysis_tool.df.drop( "rsi overbought", axis=1) stock_analysis_tool.df = stock_analysis_tool.df.drop( "rsi oversold", axis=1) @staticmethod def rsi_time_frame_text_changed(stock_analysis_tool: QMainWindow, rsi_time_frame_text: QTextEdit): """ :param stock_analysis_tool: :param rsi_time_frame_text: :return: """ text = rsi_time_frame_text.toPlainText() if text != "": try: stock_analysis_tool.rsi_n = int(text) if 'rsi' in stock_analysis_tool.df.columns: stock_analysis_tool.df = stock_analysis_tool.df.drop( "rsi", axis=1) stock_analysis_tool.df['rsi'] = rsi( close=stock_analysis_tool.df['close'], n=stock_analysis_tool.rsi_n) x = [ datetime.timestamp(date_time) for date_time in stock_analysis_tool.df.index ] stock_analysis_tool.data_lines['rsi'].setData( x, stock_analysis_tool.df['rsi']) except ValueError: print("Invalid RSI Input") @staticmethod def williams_r_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): # Add WilliamsR to Display Graph stock_analysis_tool.df['WilliamsR'] = wr( stock_analysis_tool.df['high'], stock_analysis_tool.df['low'], stock_analysis_tool.df['close']) stock_analysis_tool.df['WilliamsR overbought'] = -20 stock_analysis_tool.df['WilliamsR oversold'] = -80 stock_analysis_tool.add_column_to_graph( column_name='WilliamsR') stock_analysis_tool.add_column_to_graph( column_name='WilliamsR overbought', color=stock_analysis_tool.protected_colors['red']) stock_analysis_tool.add_column_to_graph( column_name='WilliamsR oversold', color=stock_analysis_tool.protected_colors['green']) else: # Remove WilliamsR from Display Graph stock_analysis_tool.remove_column_from_graph( column_name='WilliamsR') stock_analysis_tool.remove_column_from_graph( column_name='WilliamsR overbought') stock_analysis_tool.remove_column_from_graph( column_name='WilliamsR oversold') stock_analysis_tool.df = stock_analysis_tool.df.drop( "WilliamsR", axis=1) stock_analysis_tool.df = stock_analysis_tool.df.drop( "WilliamsR overbought", axis=1) stock_analysis_tool.df = stock_analysis_tool.df.drop( "WilliamsR oversold", axis=1) @staticmethod def cmo_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): stock_analysis_tool.df['cmo'] = chande_momentum_oscillator( close_data=stock_analysis_tool.df['close'], period=stock_analysis_tool.cmo_n) stock_analysis_tool.df['cmo overbought'] = 50 stock_analysis_tool.df['cmo oversold'] = -50 # Add CMO to Display Graph stock_analysis_tool.add_column_to_graph(column_name='cmo') stock_analysis_tool.add_column_to_graph( column_name='cmo overbought', color=stock_analysis_tool.protected_colors['red']) stock_analysis_tool.add_column_to_graph( column_name='cmo oversold', color=stock_analysis_tool.protected_colors['green']) else: # Remove CMO from Display Graph stock_analysis_tool.remove_column_from_graph(column_name='cmo') stock_analysis_tool.remove_column_from_graph( column_name='cmo overbought') stock_analysis_tool.remove_column_from_graph( column_name='cmo oversold') stock_analysis_tool.df = stock_analysis_tool.df.drop("cmo", axis=1) stock_analysis_tool.df = stock_analysis_tool.df.drop( "cmo overbought", axis=1) stock_analysis_tool.df = stock_analysis_tool.df.drop( "cmo oversold", axis=1) @staticmethod def macd_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): # Add MACD to Display Graph stock_analysis_tool.df['MACD'] = macd(close=stock_analysis_tool.df['close'], n_slow=stock_analysis_tool.macd_slow, n_fast=stock_analysis_tool.macd_fast) - \ macd_signal(close=stock_analysis_tool.df['close'], n_slow=stock_analysis_tool.macd_slow, n_fast=stock_analysis_tool.macd_fast, n_sign=stock_analysis_tool.macd_sign) stock_analysis_tool.add_column_to_graph(column_name='MACD') else: # Remove MACD from Display Graph stock_analysis_tool.remove_column_from_graph( column_name='MACD') stock_analysis_tool.df = stock_analysis_tool.df.drop("MACD", axis=1) @staticmethod def roc_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): # Add ROC to Display Graph stock_analysis_tool.df['roc'] = roc( close=stock_analysis_tool.df['close'], n=stock_analysis_tool.roc_n) stock_analysis_tool.add_column_to_graph(column_name='roc') else: # Remove ROC from Display Graph stock_analysis_tool.remove_column_from_graph(column_name='roc') stock_analysis_tool.df = stock_analysis_tool.df.drop("roc", axis=1) @staticmethod def wma_cb_pressed(cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): # Add RSI to Display Graph pass else: # Remove RSI from Display Graph pass @staticmethod def ema_cb_pressed(cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): # Add RSI to Display Graph pass else: # Remove RSI from Display Graph pass @staticmethod def sma_cb_pressed(cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): # Add RSI to Display Graph pass else: # Remove RSI from Display Graph pass @staticmethod def hma_cb_pressed(cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): # Add RSI to Display Graph pass else: # Remove RSI from Display Graph pass @staticmethod def trix_cb_pressed(cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): # Add RSI to Display Graph pass else: # Remove RSI from Display Graph pass @staticmethod def cci_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): # Add CCI to Display Graph stock_analysis_tool.df['cci'] = cci( close=stock_analysis_tool.df['close'], low=stock_analysis_tool.df['low'], high=stock_analysis_tool.df['high'], n=stock_analysis_tool.cci_n) stock_analysis_tool.add_column_to_graph(column_name='cci') else: # Remove CCI from Display Graph stock_analysis_tool.remove_column_from_graph(column_name='cci') stock_analysis_tool.df = stock_analysis_tool.df.drop("cci", axis=1) @staticmethod def dpo_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): # Add DPO to Display Graph stock_analysis_tool.df['dpo'] = dpo( close=stock_analysis_tool.df['close'], n=stock_analysis_tool.dpo_n) stock_analysis_tool.add_column_to_graph(column_name='dpo') else: # Remove DPO from Display Graph stock_analysis_tool.remove_column_from_graph(column_name='dpo') stock_analysis_tool.df = stock_analysis_tool.df.drop("dpo", axis=1) @staticmethod def cmf_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): # Add CMF to Display Graph stock_analysis_tool.df['cmf'] = chaikin_money_flow( high=stock_analysis_tool.df['high'], low=stock_analysis_tool.df['low'], close=stock_analysis_tool.df['close'], volume=stock_analysis_tool.df['volume'], n=stock_analysis_tool.cmf_n) stock_analysis_tool.add_column_to_graph(column_name='cmf') else: # Remove CMF from Display Graph stock_analysis_tool.remove_column_from_graph(column_name='cmf') stock_analysis_tool.df = stock_analysis_tool.df.drop("cmf", axis=1) @staticmethod def adx_cb_pressed(stock_analysis_tool: QMainWindow, cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): # Add ADX to Display Graph stock_analysis_tool.df['adx'] = adx( high=stock_analysis_tool.df['high'], low=stock_analysis_tool.df['low'], close=stock_analysis_tool.df['close'], n=stock_analysis_tool.adx_n) stock_analysis_tool.add_column_to_graph(column_name='adx') else: # Remove ADX from Display Graph stock_analysis_tool.remove_column_from_graph(column_name='adx') stock_analysis_tool.df = stock_analysis_tool.df.drop("adx", axis=1) @staticmethod def force_index_cb_pressed(cb: QCheckBox) -> None: """ :param cb: :return: """ if cb.isChecked(): # Add RSI to Display Graph pass else: # Remove RSI from Display Graph pass class StockSources(IntEnum): YAHOO_FIN = 0 ASTRASS = 1 YFINANCE = 2 class SampleRates(Enum): ONE_DAY = "1 Day" ONE_HOUR = "1 Hour" THIRTY_MINUTES = "30 Minutes" class TimeDeltas(Enum): MAX = "MAX" FIVE_YEARS = "5 years" ONE_YEAR = "1 year" YEAR_TO_DATE = "YTD" SIX_MONTHS = "6 months" ONE_MONTH = "1 month" FIVE_DAYS = "5 days"
class UISpritesheetExporter(object): def __init__(self): # here we don't need super().__init__(parent) # maybe it's only for who inherits extensions? self.app = krita.Krita.instance() self.exp = spritesheetexporter.SpritesheetExporter() # the main window self.mainDialog = QDialog() # the window is not modal and does not block input to other windows self.mainDialog.setWindowModality(Qt.NonModal) self.mainDialog.setMinimumSize(500, 100) # the box holding everything self.outerLayout = QVBoxLayout(self.mainDialog) self.topLayout = QVBoxLayout() # the user should choose the export name of the final spritesheet self.exportName = QLineEdit() # and the export directory self.exportDirTx = QLineEdit() self.exportDirButt = QPushButton("Change export directory") self.exportDirResetButt = QPushButton("Reset to current directory") self.exportDirResetButt.setToolTip( "Reset export directory to current .kra document's directory") self.exportDirButt.clicked.connect(self.changeExportDir) self.exportDirResetButt.clicked.connect(self.resetExportDir) self.exportDir = QHBoxLayout() # and the sprites export directory self.spritesExportDirWidget = QWidget() self.spritesExportDirTx = QLineEdit() self.spritesExportDirButt = QPushButton("Change sprites directory") self.spritesExportDirButt.clicked.connect(self.changeSpritesExportDir) self.spritesExportDirTx.setToolTip("Leave empty for default") self.spritesExportDir = QHBoxLayout(self.spritesExportDirWidget) self.customSettings = QCheckBox() self.customSettings.setChecked(False) self.customSettings.stateChanged.connect(self.toggleHideable) self.hideableWidget = QFrame() # QFrames are a type of widget self.hideableWidget.setFrameShape(QFrame.Panel) self.hideableWidget.setFrameShadow(QFrame.Sunken) self.hideableLayout = QVBoxLayout(self.hideableWidget) # we let people export each layer as an animation frame if they wish self.layersAsAnimation = QCheckBox() self.layersAsAnimation.setChecked(False) # We want to let the user choose if they want the final spritesheet # to be horizontally- or vertically-oriented. # There is a nifty thing called QButtonGroup() but # it doesn't seem to let you add names between each checkbox somehow? self.horDir = QCheckBox() self.horDir.setChecked(True) self.vertDir = QCheckBox() self.vertDir.setChecked(False) self.vertDir.stateChanged.connect(self.exclusiveVertToHor) self.horDir.stateChanged.connect(self.exclusiveHorToVert) self.direction = QHBoxLayout() self.spinBoxesWidget = QFrame() self.spinBoxesWidget.setFrameShape(QFrame.Panel) self.spinBoxesWidget.setFrameShadow(QFrame.Sunken) # a box holding the boxes with rows columns and start end self.spinBoxes = QHBoxLayout(self.spinBoxesWidget) self.rows = QSpinBox(minimum=self.exp.defaultSpace) self.columns = QSpinBox(minimum=self.exp.defaultSpace) self.rows.setValue(self.exp.defaultSpace) self.columns.setValue(self.exp.defaultSpace) self.start = QSpinBox(minimum=self.exp.defaultTime) self.end = QSpinBox(minimum=self.exp.defaultTime) self.step = QSpinBox(minimum=1) self.start.setValue(self.exp.defaultTime) self.end.setValue(self.exp.defaultTime) self.step.setValue(1) # to be placed outside of spinBoxes, still in outerLayout self.hiddenCheckbox = QWidget() self.hiddenCheckboxLayout = QVBoxLayout(self.hiddenCheckbox) self.line = QFrame() self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.checkBoxes = QHBoxLayout() self.forceNew = QCheckBox() self.forceNew.setChecked(False) self.removeTmp = QCheckBox() self.removeTmp.setChecked(True) self.line2 = QFrame() self.line2.setFrameShape(QFrame.HLine) self.line2.setFrameShadow(QFrame.Sunken) self.OkCancelButtonBox = \ QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.OkCancelButtonBox.accepted.connect(self.confirmButton) self.OkCancelButtonBox.rejected.connect(self.mainDialog.close) self.space = 10 self.spacer = QSpacerItem(self.space, self.space) self.spacerBig = QSpacerItem(self.space * 2, self.space * 2) self.exportPath = Path.home() self.initialize_export() # I would have used QFormLayout's addRow # except it doesn't let you add a tooltip to the row's name # (adding a tooltip to the whole layout would have been best # but doesn't seem possible) def addDescribedWidget(self, parent, listWidgets, align=Qt.AlignLeft): layout = QGridLayout() row = 0 for widget in listWidgets: label = QLabel(widget.descri) label.setBuddy(widget.widget) layout.addWidget(label, row, 0) layout.addWidget(widget.widget, row, 1) if widget.tooltip != "": widget.widget.setToolTip(widget.tooltip) label.setToolTip(widget.tooltip) row += 1 layout.setAlignment(align) parent.addLayout(layout) return layout def initialize_export(self): # putting stuff in boxes # and boxes in bigger boxes self.exportName.setText(self.exp.exportName) self.addDescribedWidget( parent=self.topLayout, listWidgets=[ describedWidget( widget=self.exportName, descri="Export name:", tooltip="The name of the exported spritesheet file") ]) self.addDescribedWidget( parent=self.topLayout, listWidgets=[ describedWidget( widget=self.exportDirTx, descri="Export Directory:", tooltip="The directory the spritesheet will be exported to" ) ]) self.exportDir.addWidget(self.exportDirButt) self.exportDir.addWidget(self.exportDirResetButt) self.topLayout.addLayout(self.exportDir) self.addDescribedWidget( parent=self.topLayout, listWidgets=[ describedWidget( widget=self.customSettings, descri="Use Custom export Settings:", tooltip="" + "Whether to set yourself the number of rows, columns,\n" + "first and last frame, etc. (checked)\n" + "or use the default values (unchecked) ") ]) self.outerLayout.addLayout(self.topLayout, 0) # all this stuff will be hideable self.addDescribedWidget( parent=self.hideableLayout, listWidgets=[ describedWidget( descri="use layers as animation frames ", widget=self.layersAsAnimation, tooltip="Rather than exporting a spritesheet " + "using as frames\n" + "each frame of the timeline " + "(all visible layers merged down),\n" + "export instead a spritesheet " + "using as frames\n" + "the current frame of each visible layer") ]) self.hideableLayout.addItem(self.spacer) self.direction.addWidget(QLabel("sprites placement direction: \t")) self.addDescribedWidget( parent=self.direction, listWidgets=[ describedWidget(widget=self.horDir, descri="Horizontal:", tooltip="like so:\n1, 2, 3\n4, 5, 6\n7, 8, 9") ]) self.addDescribedWidget( parent=self.direction, listWidgets=[ describedWidget(widget=self.vertDir, descri="Vertical:", tooltip="like so:\n1, 4, 7\n2, 5, 8\n3, 6, 9") ]) self.hideableLayout.addLayout(self.direction) self.hideableLayout.addItem(self.spacerBig) defaultsHint = QLabel( "Leave any parameter at 0 to get a default value:") defaultsHint.setToolTip( "For example with 16 sprites, " + "leaving both rows and columns at 0\n" + "will set their defaults to 4 each\n" + "while leaving only columns at 0 and rows at 1\n" + "will set columns default at 16") self.hideableLayout.addWidget(defaultsHint) self.addDescribedWidget( parent=self.spinBoxes, listWidgets=[ describedWidget( widget=self.rows, descri="Rows:", tooltip="Number of rows of the spritesheet;\n" + "default is assigned depending on columns number\n" + "or if 0 columns tries to form a square "), describedWidget( widget=self.columns, descri="Columns:", tooltip="Number of columns of the spritesheet;\n" + "default is assigned depending on rows number\n" + "or if 0 rows tries to form a square") ]) self.addDescribedWidget( parent=self.spinBoxes, listWidgets=[ describedWidget( widget=self.start, descri="Start:", tooltip="" + "First frame of the animation timeline (included) " + "to be added to the spritesheet;\n" + "default is first keyframe after " + "the Start frame of the Animation docker"), describedWidget( widget=self.end, descri="End:", tooltip="Last frame of the animation timeline (included) " + "to be added to the spritesheet;\n" + "default is last keyframe before " + "the End frame of the Animation docker"), describedWidget(widget=self.step, descri="Step:", tooltip="only consider every 'step' frame " + "to be added to the spritesheet;\n" + "default is 1 (use every frame)") ]) self.hideableLayout.addWidget(self.spinBoxesWidget) self.addDescribedWidget( parent=self.checkBoxes, listWidgets=[ describedWidget( descri="Remove individual sprites?", widget=self.removeTmp, tooltip="Once the spritesheet export is done,\n" + "whether to remove the individual exported sprites") ]) self.forceNewLayout = self.addDescribedWidget( parent=self.hiddenCheckboxLayout, listWidgets=[ describedWidget( descri="Force new folder?", widget=self.forceNew, tooltip="If there is already a folder " + "with the same name as the individual " + "sprites export folder,\n" + "whether to create a new one (checked) " + "or write the sprites in the existing folder,\n" + "possibly overwriting other files (unchecked)") ]) self.addDescribedWidget( parent=self.spritesExportDir, listWidgets=[ describedWidget( widget=self.spritesExportDirTx, descri="Sprites export directory:", tooltip="The directory the individual sprites " + "will be exported to") ]) self.spritesExportDir.addWidget(self.spritesExportDirButt) # have removeTmp toggle forceNew's and sprites export dir's visibility self.checkBoxes.addWidget(self.hiddenCheckbox) self.hideableLayout.addLayout(self.checkBoxes) self.hideableLayout.addWidget(self.spritesExportDirWidget) self.removeTmp.clicked.connect(self.toggleHiddenParams) self.outerLayout.addWidget(self.hideableWidget) self.outerLayout.addWidget(self.OkCancelButtonBox) self.toggleHiddenParams() self.toggleHideable() def exclusiveVertToHor(self): self.exclusiveCheckBoxUpdate(trigger=self.vertDir, triggered=self.horDir) def exclusiveHorToVert(self): self.exclusiveCheckBoxUpdate(trigger=self.horDir, triggered=self.vertDir) def exclusiveCheckBoxUpdate(self, trigger, triggered): if triggered.isChecked() == trigger.isChecked(): triggered.setChecked(not trigger.isChecked()) def toggleHideable(self): if self.customSettings.isChecked(): self.hideableWidget.show() self.mainDialog.adjustSize() else: self.hideableWidget.hide() self.mainDialog.adjustSize() def toggleHiddenParams(self): if self.removeTmp.isChecked(): self.forceNew.setChecked(False) self.spritesExportDirTx.setText("") self.hiddenCheckbox.setDisabled(self.removeTmp.isChecked()) self.spritesExportDirWidget.setDisabled(self.removeTmp.isChecked()) def showExportDialog(self): self.doc = self.app.activeDocument() if self.exportDirTx.text() == "": self.resetExportDir() self.mainDialog.setWindowTitle(i18n("SpritesheetExporter")) self.mainDialog.setSizeGripEnabled(True) self.mainDialog.show() self.mainDialog.activateWindow() self.mainDialog.setDisabled(False) def changeExportDir(self): self.exportDirDialog = QFileDialog() self.exportDirDialog.setWindowTitle(i18n("Choose Export Directory")) self.exportDirDialog.setSizeGripEnabled(True) self.exportDirDialog.setDirectory(str(self.exportPath)) # we grab the output path on directory changed self.exportPath = self.exportDirDialog.getExistingDirectory() if self.exportPath != "": self.exportDirTx.setText(str(self.exportPath)) # go back to the same folder where your .kra is def resetExportDir(self): if self.doc and self.doc.fileName(): self.exportPath = Path(self.doc.fileName()).parents[0] self.exportDirTx.setText(str(self.exportPath)) def changeSpritesExportDir(self): self.SpritesExportDirDialog = QFileDialog() self.SpritesExportDirDialog.setWindowTitle( i18n("Choose Sprites Export Directory")) self.SpritesExportDirDialog.setSizeGripEnabled(True) self.SpritesExportDirDialog.setDirectory(str(self.exportPath)) # we grab the output path on directory changed self.spritesExportPath = \ self.SpritesExportDirDialog.getExistingDirectory() if self.spritesExportPath != "": self.spritesExportDirTx.setText(str(self.spritesExportPath)) def confirmButton(self): # if you double click it shouldn't interrupt # the first run of the function with a new one self.mainDialog.setDisabled(True) self.exp.exportName = self.exportName.text().split('.')[0] self.exp.exportDir = Path(self.exportPath) self.exp.layersAsAnimation = self.layersAsAnimation.isChecked() self.exp.isDirectionHorizontal = self.horDir.isChecked() self.exp.rows = self.rows.value() self.exp.columns = self.columns.value() self.exp.start = self.start.value() self.exp.end = self.end.value() self.exp.step = self.step.value() self.exp.removeTmp = self.removeTmp.isChecked() self.exp.forceNew = self.forceNew.isChecked() if self.spritesExportDirTx.text() != "": self.exp.spritesExportDir = Path(self.spritesExportDirTx.text()) else: # important: we reset spritesheetexporter's spritesExportDir self.exp.spritesExportDir = self.exp.defaultPath self.exp.export() self.mainDialog.hide()
def initUI(self): # ==================== FRAME ENCABEZADO ==================== paleta = QPalette() paleta.setColor(QPalette.Background, QColor(51, 0, 102)) frame = QFrame(self) frame.setFrameShape(QFrame.NoFrame) frame.setFrameShadow(QFrame.Sunken) frame.setAutoFillBackground(True) frame.setPalette(paleta) frame.setFixedWidth(400) frame.setFixedHeight(84) frame.move(0, 0) labelIcono = QLabel(frame) labelIcono.setFixedWidth(40) labelIcono.setFixedHeight(40) labelIcono.setPixmap( QPixmap("icono.png").scaled(40, 40, Qt.KeepAspectRatio, Qt.SmoothTransformation)) labelIcono.move(37, 22) fuenteTitulo = QFont() fuenteTitulo.setPointSize(16) fuenteTitulo.setBold(True) labelTitulo = QLabel("<font color='white'>Login</font>", frame) labelTitulo.setFont(fuenteTitulo) labelTitulo.move(83, 20) # ===================== WIDGETS LOGIN ====================== # ======================================================== labelUsuario = QLabel("Usuario", self) labelUsuario.move(60, 120) frameUsuario = QFrame(self) frameUsuario.setFrameShape(QFrame.StyledPanel) frameUsuario.setFixedWidth(280) frameUsuario.setFixedHeight(28) frameUsuario.move(60, 146) self.lineEditUsuario = QLineEdit(frameUsuario) self.lineEditUsuario.setFrame(False) self.lineEditUsuario.setTextMargins(8, 0, 4, 1) self.lineEditUsuario.setFixedWidth(238) self.lineEditUsuario.setFixedHeight(26) self.lineEditUsuario.move(40, 1) # ======================================================== labelContrasenia = QLabel("Contraseña", self) labelContrasenia.move(60, 174) frameContrasenia = QFrame(self) frameContrasenia.setFrameShape(QFrame.StyledPanel) frameContrasenia.setFixedWidth(280) frameContrasenia.setFixedHeight(28) frameContrasenia.move(60, 200) self.lineEditContrasenia = QLineEdit(frameContrasenia) self.lineEditContrasenia.setFrame(False) self.lineEditContrasenia.setEchoMode(QLineEdit.Password) self.lineEditContrasenia.setTextMargins(8, 0, 4, 1) self.lineEditContrasenia.setFixedWidth(238) self.lineEditContrasenia.setFixedHeight(26) self.lineEditContrasenia.move(40, 1) labelToken = QLabel("Token", self) labelToken.move(60, 224) frameToken = QFrame(self) frameToken.setFrameShape(QFrame.StyledPanel) frameToken.setFixedWidth(280) frameToken.setFixedHeight(28) frameToken.move(60, 250) self.lineEditToken = QLineEdit(frameToken) self.lineEditToken.setFrame(False) self.lineEditToken.setEchoMode(QLineEdit.Password) self.lineEditToken.setTextMargins(8, 0, 4, 1) self.lineEditToken.setFixedWidth(238) self.lineEditToken.setFixedHeight(26) self.lineEditToken.move(40, 1) # ================== WIDGETS QPUSHBUTTON =================== buttonLogin = QPushButton("Iniciar sesión", self) buttonLogin.setFixedWidth(135) buttonLogin.setFixedHeight(28) buttonLogin.move(60, 286) buttonCancelar = QPushButton("Cancelar", self) buttonCancelar.setFixedWidth(135) buttonCancelar.setFixedHeight(28) buttonCancelar.move(205, 286) # ==================== MÁS INFORMACIÓN ===================== # ==================== SEÑALES BOTONES ===================== buttonLogin.clicked.connect(self.Login) buttonCancelar.clicked.connect(self.close)
def __init__(self, parent, db_path, file_name): QWidget.__init__(self, parent) # Получаем рисунок и помещаем его в виджет con = sqlite3.connect(db_path) cur = con.cursor() sql_item_img_select = "SELECT item_img FROM nomenclature WHERE item_name = ?" cur.execute(sql_item_img_select, [file_name]) item_img = cur.fetchone() pix = QPixmap(item_img[0]) pix_mini = pix.scaled(350, 290, QtCore.Qt.KeepAspectRatio) img_lbl = QLabel() img_lbl.setPixmap(pix_mini) img_lbl_vbox = QVBoxLayout() img_lbl_vbox.addWidget(img_lbl) img_lbl_frame = QFrame() img_lbl_frame.setLayout(img_lbl_vbox) img_lbl_frame.setFixedSize(350, 290) # Получаем все данные для товара # -номер sql_item_numb_select = "SELECT item_numb FROM nomenclature WHERE item_name = ?" cur.execute(sql_item_numb_select, [file_name]) item_numb = cur.fetchone() # -название sql_item_name_select = "SELECT item_name FROM nomenclature WHERE item_name = ?" cur.execute(sql_item_name_select, [file_name]) item_name = cur.fetchone() # -ед.изм. sql_item_unit_select = "SELECT item_unit FROM nomenclature WHERE item_name = ?" cur.execute(sql_item_unit_select, [file_name]) item_unit = cur.fetchone() # -категория sql_item_cat_select = "SELECT item_cat FROM nomenclature WHERE item_name = ?" cur.execute(sql_item_cat_select, [file_name]) item_cat = cur.fetchone() # -количество sql_item_amount_select = "SELECT item_amount FROM items_positions WHERE item_name = ?" # -поставщики sql_item_sup_select = "SELECT DISTINCT supp FROM ro_orders WHERE name = ?" # Проверяем, есть ли товар в наличии и только тогда выводим количество # и поставщиков sql_item_cur_select = "SELECT DISTINCT name FROM ro_orders WHERE name = ?" cur.execute(sql_item_cur_select, [file_name]) item_cur = cur.fetchone() if item_cur is not None: cur.execute(sql_item_amount_select, [file_name]) item_amount = cur.fetchone() cur.execute(sql_item_sup_select, [file_name]) item_supp = cur.fetchall() suppliers_str = '' k = 1 for el in item_supp[0]: if k != len(item_supp): suppliers_str = suppliers_str + el + ',' else: suppliers_str = suppliers_str + el k = k + 1 item_amount_str = str(item_amount[0]) else: item_amount_str = 'Товар не в наличии' suppliers_str = 'Товар не в наличии' # Формируем таблицу item_card_table = QTableWidget() item_card_table.setRowCount(6) item_card_table.setColumnCount(1) item_card_table.horizontalHeader().hide() item_card_table.setFixedSize(210, 185) item_card_table.horizontalHeader().resizeSection(0, 125) #horizontal # столбец - номер item_card_table.verticalHeader().resizeSection(0, 30) item_card_table.verticalHeader().setSectionResizeMode( 0, QHeaderView.Fixed) item_card_table.verticalHeader().minimumSectionSize() column_1 = QTableWidgetItem() column_1.setText("№") item_card_table.setVerticalHeaderItem(0, column_1) item_card_table.verticalHeader().setStyleSheet("color: steelblue") item_numb_lbl = QLabel(str(item_numb[0])) item_card_table.setCellWidget(0, 0, item_numb_lbl) # столбец - название item_card_table.verticalHeader().resizeSection(1, 30) item_card_table.verticalHeader().setSectionResizeMode( 1, QHeaderView.Fixed) column_2 = QTableWidgetItem() column_2.setText("Название") item_card_table.setVerticalHeaderItem(1, column_2) item_card_table.verticalHeader().setStyleSheet("color: steelblue") item_name_lbl = QLabel(item_name[0]) item_card_table.setCellWidget(1, 0, item_name_lbl) # столбец - ед.изм item_card_table.verticalHeader().resizeSection(2, 30) item_card_table.verticalHeader().setSectionResizeMode( 2, QHeaderView.Fixed) column_3 = QTableWidgetItem() column_3.setText("Ед.изм.") item_card_table.setVerticalHeaderItem(2, column_3) item_card_table.verticalHeader().setStyleSheet("color: steelblue") item_unit_lbl = QLabel(item_unit[0]) item_card_table.setCellWidget(2, 0, item_unit_lbl) # столбец - категория item_card_table.verticalHeader().resizeSection(3, 30) item_card_table.verticalHeader().setSectionResizeMode( 3, QHeaderView.Fixed) column_4 = QTableWidgetItem() column_4.setText("Категория") item_card_table.setVerticalHeaderItem(3, column_4) item_card_table.verticalHeader().setStyleSheet("color: steelblue") item_cat_lbl = QLabel(item_cat[0]) item_card_table.setCellWidget(3, 0, item_cat_lbl) # столбец - количество item_card_table.verticalHeader().resizeSection(4, 30) item_card_table.verticalHeader().setSectionResizeMode( 4, QHeaderView.Fixed) column_5 = QTableWidgetItem() column_5.setText("Количество") item_card_table.setVerticalHeaderItem(4, column_5) item_card_table.verticalHeader().setStyleSheet("color: steelblue") item_amount_lbl = QLabel(item_amount_str) item_card_table.setCellWidget(4, 0, item_amount_lbl) # столбец - поставщики item_card_table.verticalHeader().resizeSection(5, 30) item_card_table.verticalHeader().setSectionResizeMode( 5, QHeaderView.Fixed) column_6 = QTableWidgetItem() column_6.setText("Поставщики") item_card_table.setVerticalHeaderItem(5, column_6) item_card_table.verticalHeader().setStyleSheet("color: steelblue") item_supp_lbl = QLabel(suppliers_str) item_card_table.setCellWidget(5, 0, item_supp_lbl) cur.close() con.close() item_prs_grid = QGridLayout() item_prs_grid.addWidget(img_lbl_frame, 0, 0, alignment=QtCore.Qt.AlignCenter) item_prs_grid.addWidget(item_card_table, 1, 0, alignment=QtCore.Qt.AlignCenter) scrollArea = QScrollArea() scrollArea.setWidgetResizable(True) scrollArea.setLayout(item_prs_grid) scrollArea.setFixedSize(600, 518) fQMD_grid = QGridLayout() fQMD_grid.addWidget(scrollArea, 0, 0, alignment=QtCore.Qt.AlignCenter) fQMD_frame = QFrame() fQMD_frame.setStyleSheet( open("./styles/properties_form_style.qss", "r").read()) fQMD_frame.setFrameShape(QFrame.Panel) fQMD_frame.setFrameShadow(QFrame.Sunken) fQMD_frame.setLayout(fQMD_grid) fQMD_vbox = QVBoxLayout() fQMD_vbox.addWidget(fQMD_frame) # Размещение на форме всех компонентов form = QFormLayout() form.addRow(fQMD_vbox) self.setLayout(form)
def __init__(self, *args): super().__init__(BrickletAmbientLightV3, *args) self.al = self.device self.cbe_illuminance = CallbackEmulator(self.al.get_illuminance, None, self.cb_illuminance, self.increase_error_count) self.alf = ColorFrame(25, 25, QColor(128, 128, 128)) self.out_of_range_label = QLabel('Illuminance is out-of-range') self.saturated_label = QLabel('Sensor is saturated') self.out_of_range_label.hide() self.out_of_range_label.setStyleSheet('QLabel { color: red }') self.saturated_label.hide() self.saturated_label.setStyleSheet('QLabel { color: magenta }') self.current_illuminance = CurveValueWrapper() # float, lx plots = [('Illuminance', Qt.red, self.current_illuminance, '{:.2f} lx (Lux)'.format)] self.plot_widget = PlotWidget('Illuminance [lx]', plots, extra_key_widgets=[ self.out_of_range_label, self.saturated_label, self.alf ], y_resolution=0.001) self.range_label = QLabel('Illuminance Range:') self.range_combo = QComboBox() self.range_combo.addItem( "Unlimited", BrickletAmbientLightV3.ILLUMINANCE_RANGE_UNLIMITED) self.range_combo.addItem( "0 - 64000 lx", BrickletAmbientLightV3.ILLUMINANCE_RANGE_64000LUX) self.range_combo.addItem( "0 - 32000 lx", BrickletAmbientLightV3.ILLUMINANCE_RANGE_32000LUX) self.range_combo.addItem( "0 - 16000 lx", BrickletAmbientLightV3.ILLUMINANCE_RANGE_16000LUX) self.range_combo.addItem( "0 - 8000 lx", BrickletAmbientLightV3.ILLUMINANCE_RANGE_8000LUX) self.range_combo.addItem( "0 - 1300 lx", BrickletAmbientLightV3.ILLUMINANCE_RANGE_1300LUX) self.range_combo.addItem( "0 - 600 lx", BrickletAmbientLightV3.ILLUMINANCE_RANGE_600LUX) self.range_combo.currentIndexChanged.connect(self.new_config) self.time_label = QLabel('Integration Time:') self.time_combo = QComboBox() self.time_combo.addItem("50 ms", BrickletAmbientLightV3.INTEGRATION_TIME_50MS) self.time_combo.addItem("100 ms", BrickletAmbientLightV3.INTEGRATION_TIME_100MS) self.time_combo.addItem("150 ms", BrickletAmbientLightV3.INTEGRATION_TIME_150MS) self.time_combo.addItem("200 ms", BrickletAmbientLightV3.INTEGRATION_TIME_200MS) self.time_combo.addItem("250 ms", BrickletAmbientLightV3.INTEGRATION_TIME_250MS) self.time_combo.addItem("300 ms", BrickletAmbientLightV3.INTEGRATION_TIME_300MS) self.time_combo.addItem("350 ms", BrickletAmbientLightV3.INTEGRATION_TIME_350MS) self.time_combo.addItem("400 ms", BrickletAmbientLightV3.INTEGRATION_TIME_400MS) self.time_combo.currentIndexChanged.connect(self.new_config) hlayout = QHBoxLayout() hlayout.addWidget(self.range_label) hlayout.addWidget(self.range_combo) hlayout.addStretch() hlayout.addWidget(self.time_label) hlayout.addWidget(self.time_combo) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
class UiGameFrame(QFrame): def __init__(self, parent): super(UiGameFrame, self).__init__(parent) self.setupUi() def setupUi(self): # 游戏界面 self.setGeometry(QRect(10, 10, 671, 711)) # self.setStyleSheet("background-image: url(./img/bg.bmp);") self.setFrameShape(QFrame.Box) self.setFrameShadow(QFrame.Sunken) self.setLineWidth(2) self.setObjectName("uiGameFrame") # 房间信息 self.game_info = QLabel(self) self.game_info.setGeometry(QRect(20, 5, 631, 40)) self.game_info.setObjectName("gameInfo") self.game_info.setScaledContents(True) self.game_info.setStyleSheet( 'font-size:20px;font-weight:bold;') self.game_info.setAlignment(Qt.AlignCenter | Qt.AlignTop) # 游戏画面 self.game_frame = QFrame(self) self.game_frame.setGeometry(QRect(80, 145, 504, 504)) # self.game_frame.setStyleSheet("background-image: url(./img/game.bmp);") self.game_frame.setFrameShape(QFrame.Box) self.game_frame.setFrameShadow(QFrame.Plain) self.game_frame.setObjectName("gameFrame") # 对战 self.vs_frame = QFrame(self) self.vs_frame.setGeometry(QRect(50, 55, 270, 80)) self.vs_frame.setFrameShape(QFrame.StyledPanel) self.vs_frame.setFrameShadow(QFrame.Raised) self.vs_frame.setObjectName("vsFrame") # self.vs_frame.setStyleSheet("border:1px solid;") self.vs_user_image = QLabel(self.vs_frame) self.vs_user_image.setGeometry(QRect(5, 5, 70, 70)) self.vs_user_image.setObjectName("vsUserImage") self.vs_user_image.setScaledContents(True) self.vs_user_info = QLabel(self.vs_frame) self.vs_user_info.setGeometry(QRect(80, 5, 120, 70)) self.vs_user_info.setObjectName("vsUserInfo") self.lcdNumber_l = QLCDNumber(self.vs_frame) self.lcdNumber_l.setGeometry(QRect(205, 5, 60, 70)) self.lcdNumber_l.setLineWidth(0) self.lcdNumber_l.setDigitCount(2) self.lcdNumber_l.setSegmentStyle(QLCDNumber.Flat) self.lcdNumber_l.setProperty("intValue", 20) self.lcdNumber_l.setObjectName("lcdNumber_2") self.vs_frame_r = QFrame(self) self.vs_frame_r.setGeometry(QRect(350, 55, 270, 80)) self.vs_frame_r.setFrameShape(QFrame.StyledPanel) self.vs_frame_r.setFrameShadow(QFrame.Raised) self.vs_frame_r.setObjectName("vsFrameR") # self.vs_frame_r.setStyleSheet("border:1px solid;") self.lcdNumber_r = QLCDNumber(self.vs_frame_r) self.lcdNumber_r.setGeometry(QRect(5, 5, 60, 70)) self.lcdNumber_r.setLineWidth(0) self.lcdNumber_r.setDigitCount(2) self.lcdNumber_r.setSegmentStyle(QLCDNumber.Flat) self.lcdNumber_r.setProperty("intValue", 20) self.lcdNumber_r.setObjectName("lcdNumber_3") self.vs_user_image_r = QLabel(self.vs_frame_r) self.vs_user_image_r.setGeometry(QRect(70, 5, 70, 70)) self.vs_user_image_r.setObjectName("vsUserImageR") self.vs_user_image_r.setScaledContents(True) self.vs_user_info_r = QLabel(self.vs_frame_r) self.vs_user_info_r.setGeometry(QRect(145, 5, 120, 70)) self.vs_user_info_r.setObjectName("vsUserInfoR") # 按钮区域 self.cmd_frame = QFrame(self) self.cmd_frame.setGeometry(QRect(55, 655, 560, 47)) self.cmd_frame.setFrameShape(QFrame.StyledPanel) self.cmd_frame.setFrameShadow(QFrame.Raised) self.cmd_frame.setObjectName("cmdFrame") # 开始按钮 self.gameStartBtn = QPushButton(self.cmd_frame) self.gameStartBtn.setGeometry(QRect(10, 10, 100, 27)) self.gameStartBtn.setObjectName("gameStartBtn") # 悔棋按钮 self.gameUndoBtn = QPushButton(self.cmd_frame) self.gameUndoBtn.setGeometry(QRect(120, 10, 100, 27)) self.gameUndoBtn.setObjectName("gameUndoBtn") # 认输按钮 self.gameGiveupBtn = QPushButton(self.cmd_frame) self.gameGiveupBtn.setGeometry(QRect(230, 10, 100, 27)) self.gameGiveupBtn.setObjectName("gameGiveupBtn") # 返回大厅 self.gameReHallBtn = QPushButton(self.cmd_frame) self.gameReHallBtn.setGeometry(QRect(340, 10, 100, 27)) self.gameReHallBtn.setObjectName("gameReHallBtn") # 设置 self.gameSetBtn = QPushButton(self.cmd_frame) self.gameSetBtn.setGeometry(QRect(450, 10, 100, 27)) self.gameSetBtn.setObjectName("gameSetBtn") self.retranslateUi() QMetaObject.connectSlotsByName(self) def retranslateUi(self): _translate = QCoreApplication.translate self.gameStartBtn.setText(_translate("MainWindow", "开始游戏")) self.gameUndoBtn.setText(_translate("MainWindow", "悔棋")) self.gameGiveupBtn.setText(_translate("MainWindow", "认输")) self.gameReHallBtn.setText(_translate("MainWindow", "返回大厅")) self.gameSetBtn.setText(_translate("MainWindow", "设置"))
def init_ui(self): top_layout = QVBoxLayout() top_layout.setContentsMargins(10, 10, 10, 10) top_layout.setSpacing(15) # # Top "message box" / time remaining # message_layout = QHBoxLayout() self.status_label = QLabel("Waiting for Preparation...") self.status_label.setStyleSheet(" font-weight: bold; font-size: 18pt; " " color: red;") self.status_label.setAlignment(Qt.AlignCenter) self.progress_label = QLabel("0.0s (1 / 1)") self.progress_label.setStyleSheet(" font-size: 16pt; color: black;") self.progress_label.setAlignment(Qt.AlignCenter) message_layout.addWidget(self.status_label) message_layout.addWidget(self.progress_label) message_layout.setStretch(0, 66) message_layout.setStretch(1, 33) top_layout.addLayout(message_layout) # # Video player # video_layout = QHBoxLayout() self.video_player = QMediaPlayer(None, QMediaPlayer.VideoSurface) video_widget = QVideoWidget() self.video_player.setVideoOutput(video_widget) video_layout.addWidget(video_widget) descrip_layout = QVBoxLayout() self.desc_title = QLabel("No Movement") self.desc_title.setStyleSheet( "border: 4px solid gray; font-weight: bold; font-size: 14pt;") self.desc_title.setAlignment(Qt.AlignCenter) self.desc_explain = QTextEdit("No description available.") self.desc_explain.setStyleSheet( "border: 4px solid gray; font-size: 12pt; border-color: black;") self.desc_explain.setReadOnly(True) descrip_layout.addWidget(self.desc_title) descrip_layout.addWidget(self.desc_explain) video_layout.addLayout(descrip_layout) video_layout.setStretch(0, 66) video_layout.setStretch(1, 33) top_layout.addLayout(video_layout) # # Preparation Box # parameters_box = QGroupBox() parameters_box.setTitle("Preparation Phase") parameters_box.setObjectName("CollecParamBox") parameters_box.setStyleSheet( "QGroupBox#CollecParamBox { border: 1px solid gray; border-radius: 7px; margin-top: 2em;" " font-weight: bold; background-color: #dddddd;}" "QGroupBox#CollecParamBox::title { subcontrol-origin: margin; subcontrol-position: top center; " " border: 1px solid gray; border-radius: 7px;" "padding-left: 10px; " "padding-right: 10px;}") font = parameters_box.font() font.setPointSize(16) parameters_box.setFont(font) parameters_box.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) top_layout.addWidget(parameters_box) prep_layout = QHBoxLayout() prep_layout.setSpacing(10) parameters_box.setLayout(prep_layout) # # Preparation Box: Model Selection # model_select = QGridLayout() model_select.setContentsMargins(0, 0, 10, 0) model_button = QPushButton("Select Model") model_button.setStyleSheet("font-weight: bold") model_select.addWidget(model_button, 0, 0, 1, 2) hline = QFrame() hline.setFrameShape(QFrame.HLine) hline.setFrameShadow(QFrame.Sunken) model_select.addWidget(hline, 1, 0, 1, 2) name_title = QLabel("Name") model_select.addWidget(name_title, 2, 0) samples_title = QLabel("Samples") model_select.addWidget(samples_title, 3, 0) self.model_name = QLineEdit() self.model_name.setReadOnly(True) model_select.addWidget(self.model_name, 2, 1) self.samples_field = QLineEdit() self.samples_field.setReadOnly(True) model_select.addWidget(self.samples_field, 3, 1) prep_layout.addLayout(model_select) model_select.setRowStretch(0, 2) model_select.setRowStretch(1, 1) model_select.setRowStretch(2, 2) model_select.setRowStretch(3, 2) # Note: No copy constructors for Qt5 objects... vline = QFrame() vline.setFrameShape(QFrame.VLine) vline.setFrameShadow(QFrame.Sunken) vline2 = QFrame() vline2.setFrameShape(QFrame.VLine) vline2.setFrameShadow(QFrame.Sunken) vline3 = QFrame() vline3.setFrameShape(QFrame.VLine) vline3.setFrameShadow(QFrame.Sunken) prep_layout.addWidget(vline) # # Preparation Box: Generate Noise Model # noise_layout = QVBoxLayout() noise_button = QPushButton("Collect Noise") noise_button.setStyleSheet("font-weight: bold") noise_layout.addWidget(noise_button) collect_title = QLabel("Duration") collect_title.setAlignment(Qt.AlignCenter | Qt.AlignBottom) hline2 = QFrame() hline2.setFrameShape(QFrame.HLine) hline2.setFrameShadow(QFrame.Sunken) noise_layout.addWidget(hline2) noise_layout.addWidget(collect_title) self.noise_duration = QLineEdit("15.0") self.noise_duration.setAlignment(Qt.AlignCenter) noise_layout.addWidget(self.noise_duration) prep_layout.addLayout(noise_layout) prep_layout.addWidget(vline2) noise_layout.setStretch(0, 2) noise_layout.setStretch(1, 1) noise_layout.setStretch(2, 2) noise_layout.setStretch(3, 2) # # Preparation Box: Devices Connected # connected_layout = QVBoxLayout() connected_title = QLabel("Devices Connected") connected_title.setAlignment(Qt.AlignCenter) connected_title.setStyleSheet("font-weight: bold") connected_layout.addWidget(connected_title) self.devices_connected = QPushButton() #self.devices_connected.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) hline3 = QFrame() hline3.setFrameShape(QFrame.HLine) hline3.setFrameShadow(QFrame.Sunken) connected_layout.addWidget(hline3) connected_layout.setStretchFactor(connected_title, 2) connected_layout.setStretchFactor(hline3, 1) connected_layout.setStretchFactor(self.devices_connected, 4) connected_layout.addWidget(self.devices_connected) prep_layout.addLayout(connected_layout) prep_layout.addWidget(vline3) # # Online Testing Parameters # param_layout = QGridLayout() test_title = QLabel("Test Parameters") test_title.setAlignment(Qt.AlignCenter) test_title.setStyleSheet("font-weight: bold") param_layout.addWidget(test_title, 0, 0, 1, 2) hline4 = QFrame() hline4.setFrameShape(QFrame.HLine) hline4.setFrameShadow(QFrame.Sunken) param_layout.addWidget(hline4, 1, 0, 1, 2) self.pred_min_duration = QLineEdit("2.0") self.pred_max_duration = QLineEdit("4.0") self.min_title = QLabel("<b>(Min)</b> Duration") self.max_title = QLabel("<b>(Max)</b> Duration") param_layout.addWidget(self.min_title, 2, 0) param_layout.addWidget(self.max_title, 3, 0) param_layout.addWidget(self.pred_min_duration, 2, 1) param_layout.addWidget(self.pred_max_duration, 3, 1) prep_layout.addLayout(param_layout) # # Preparation Phase formatting # prep_layout.setStretchFactor(model_select, 4) prep_layout.setStretchFactor(noise_layout, 2) prep_layout.setStretchFactor(connected_layout, 5) prep_layout.setStretchFactor(param_layout, 4) top_layout.setStretch(0, 1) top_layout.setStretch(1, 15) top_layout.setStretch(2, 3) self.setLayout(top_layout)
def __init__(self, *args): super().__init__(BrickletAccelerometerV2, *args) self.accelerometer = self.device self.cbe_acceleration = CallbackEmulator(self.accelerometer.get_acceleration, None, self.cb_acceleration, self.increase_error_count, expand_result_tuple_for_callback=True) self.current_acceleration_x = CurveValueWrapper() # float, g self.current_acceleration_y = CurveValueWrapper() # float, g self.current_acceleration_z = CurveValueWrapper() # float, g self.pitch_label = PitchLabel() self.roll_label = RollLabel() plots = [('X', Qt.red, self.current_acceleration_x, '{:.4f} g'.format), ('Y', Qt.darkGreen, self.current_acceleration_y, '{:.4f} g'.format), ('Z', Qt.blue, self.current_acceleration_z, '{:.4f} g'.format)] self.plot_widget = PlotWidget('Acceleration [g]', plots, extra_key_widgets=[self.pitch_label, self.roll_label], update_interval=0.05, y_resolution=0.0001) self.fs_label = QLabel('Full Scale:') self.fs_combo = QComboBox() self.fs_combo.addItem("2 g") self.fs_combo.addItem("4 g") self.fs_combo.addItem("8 g") self.fs_combo.currentIndexChanged.connect(self.new_config) self.dr_label = QLabel('Data Rate:') self.dr_combo = QComboBox() self.dr_combo.addItem("0.781 Hz") self.dr_combo.addItem("1.563 Hz") self.dr_combo.addItem("3.125 Hz") self.dr_combo.addItem("6.2512 Hz") self.dr_combo.addItem("12.5 Hz") self.dr_combo.addItem("25 Hz") self.dr_combo.addItem("50 Hz") self.dr_combo.addItem("100 Hz") self.dr_combo.addItem("200 Hz") self.dr_combo.addItem("400 Hz") self.dr_combo.addItem("800 Hz") self.dr_combo.addItem("1600 Hz") self.dr_combo.addItem("3200 Hz") self.dr_combo.addItem("6400 Hz") self.dr_combo.addItem("12800 Hz") self.dr_combo.addItem("25600 Hz") self.dr_combo.currentIndexChanged.connect(self.new_config) hlayout = QHBoxLayout() hlayout.addStretch() hlayout.addWidget(self.fs_label) hlayout.addWidget(self.fs_combo) hlayout.addStretch() hlayout.addWidget(self.dr_label) hlayout.addWidget(self.dr_combo) hlayout.addStretch() line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
class UIFilterManager(object): def __init__(self): self.mainDialog = filtermanagerdialog.FilterManagerDialog() self.mainLayout = QVBoxLayout(self.mainDialog) self.formLayout = QFormLayout() self.buttonBox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.kritaInstance = krita.Krita.instance() self._filters = sorted(self.kritaInstance.filters()) self._documents = self.kritaInstance.documents() self.treeModel = filtermanagertreemodel.FilterManagerTreeModel(self) self.documentsTreeView = QTreeView() self.filterComboBox = filtercombobox.FilterComboBox(self) self.buttonBox.accepted.connect(self.confirmButton) self.buttonBox.rejected.connect(self.mainDialog.close) self.documentsTreeView.setSelectionMode( QAbstractItemView.SingleSelection) self.mainDialog.setWindowModality(Qt.NonModal) def initialize(self): self.documentsTreeView.setModel(self.treeModel) self.documentsTreeView.setWindowTitle(i18n("Document Tree Model")) self.documentsTreeView.resizeColumnToContents(0) self.documentsTreeView.resizeColumnToContents(1) self.documentsTreeView.resizeColumnToContents(2) self.formLayout.addRow(i18nc("Python filters", "Filters:"), self.filterComboBox) self.line = QFrame() self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.mainLayout.addWidget(self.documentsTreeView) self.mainLayout.addLayout(self.formLayout) self.mainLayout.addWidget(self.line) self.mainLayout.addWidget(self.buttonBox) self.mainDialog.resize(500, 300) self.mainDialog.setWindowTitle(i18n("Filter Manager")) self.mainDialog.setSizeGripEnabled(True) self.mainDialog.show() self.mainDialog.activateWindow() def confirmButton(self): documentsIndexes = [] selectionModel = self.documentsTreeView.selectionModel() for index in selectionModel.selectedRows(): node = self.treeModel.data(index, Qt.UserRole + 1) documentIndex = self.treeModel.data(index, Qt.UserRole + 2) _type = self.treeModel.data(index, Qt.UserRole + 3) if _type == 'Document': self.applyFilterOverDocument(self.documents[documentIndex]) else: self.applyFilterOverNode(node, self.documents[documentIndex]) documentsIndexes.append(documentIndex) self.refreshDocumentsProjections(set(documentsIndexes)) def refreshDocumentsProjections(self, indexes): for index in indexes: document = self.documents[index] document.refreshProjection() def applyFilterOverNode(self, node, document): _filter = self.kritaInstance.filter(self.filterComboBox.currentText()) _filter.apply(node, 0, 0, document.width(), document.height()) def applyFilterOverDocument(self, document): """This method applies the selected filter just to topLevelNodes, then if topLevelNodes are GroupLayers, that filter will not be applied.""" for node in document.topLevelNodes(): self.applyFilterOverNode(node, document) @property def filters(self): return self._filters @property def documents(self): return self._documents
def __init__(self, *args): super().__init__(BrickletCompass, *args) self.compass = self.device self.cbe_mfd = CallbackEmulator(self.compass.get_magnetic_flux_density, None, self.cb_mfd, self.increase_error_count) self.calibration = None self.compass_widget = CompassWidget() self.current_mfd_x = CurveValueWrapper() # int, mG self.current_mfd_y = CurveValueWrapper() # int, mG self.current_mfd_z = CurveValueWrapper() # int, mG self.heading_label = HeadingLabel() self.inclination_label = InclinationLabel() self.label_widget = QWidget() self.label_layout = QVBoxLayout() self.label_layout.addWidget(self.heading_label) self.label_layout.addWidget(self.inclination_label) self.label_widget.setLayout(self.label_layout) plots = [('X', Qt.red, self.current_mfd_x, '{0} mG'.format), ('Y', Qt.darkGreen, self.current_mfd_y, '{0} mG'.format), ('Z', Qt.blue, self.current_mfd_z, '{0} mG'.format)] self.plot_widget = PlotWidget('Magnetic Flux Density [mG]', plots, extra_key_widgets=[self.compass_widget, self.label_widget], update_interval=0.1, y_resolution=1) self.dr_label = QLabel('Data Rate:') self.dr_combo = QComboBox() self.dr_combo.addItem("100 Hz") self.dr_combo.addItem("200 Hz") self.dr_combo.addItem("400 Hz") self.dr_combo.addItem("600 Hz") self.dr_combo.currentIndexChanged.connect(self.new_config) self.button_calibration = QPushButton('Calibrate') self.button_calibration.clicked.connect(self.calibration_clicked) hlayout = QHBoxLayout() hlayout.addStretch() hlayout.addWidget(self.dr_label) hlayout.addWidget(self.dr_combo) hlayout.addStretch() hlayout.addWidget(self.button_calibration) hlayout.addStretch() line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
def __init__(self): super(self.__class__, self).__init__() self.setWindowTitle("CardiAP") label = QLabel( 'Please select the path and the file format for the export') label.setWordWrap(True) file_path_form = QWidget() file_path_form_layout = QFormLayout(file_path_form) path_label = QLabel("Selected directory", file_path_form) self.path_input = QLineEdit(file_path_form) self.path_input.setReadOnly(True) select_path_button = QPushButton("Select the directory") select_path_button.clicked.connect(self.select_path) file_path_form_layout.setWidget(0, QFormLayout.LabelRole, path_label) file_path_form_layout.setWidget(0, QFormLayout.FieldRole, self.path_input) file_path_form_layout.setWidget(1, QFormLayout.LabelRole, select_path_button) file_path_form.setLayout(file_path_form_layout) line = QFrame(self) line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) csv_checkbox = QCheckBox() csv_checkbox.setText('CSV') csv_checkbox.clicked.connect(lambda: self.export_format_selected.emit(DataExportController.CSV_FORMAT)) json_checkbox = QCheckBox() json_checkbox.setText('JSON') json_checkbox.clicked.connect(lambda: self.export_format_selected.emit(DataExportController.JSON_FORMAT)) xslx_checkbox = QCheckBox() xslx_checkbox.setText('XSLX') xslx_checkbox.clicked.connect(lambda: self.export_format_selected.emit(DataExportController.XLSX_FORMAT)) format_form = QWidget() format_form_layout = QFormLayout() format_form.setLayout(format_form_layout) format_form_layout.setWidget(0, QFormLayout.FieldRole, csv_checkbox) format_form_layout.setWidget(1, QFormLayout.FieldRole, json_checkbox) format_form_layout.setWidget(2, QFormLayout.FieldRole, xslx_checkbox) ok_button = QPushButton('Save data') ok_button.clicked.connect(self.finish_with_settings.emit) self.buttonBox = QDialogButtonBox() self.buttonBox.addButton(ok_button, QDialogButtonBox.ActionRole) self.layout = QVBoxLayout() self.layout.addWidget(label) self.layout.addWidget(file_path_form) self.layout.addWidget(line) self.layout.addWidget(format_form) self.layout.addWidget(self.buttonBox) self.setLayout(self.layout)
def initUI(self): frame = QFrame() # frame.setStyleSheet("background-color: rgb(30, 45, 66);") frame.setFrameShape(QFrame.StyledPanel) frame.setFrameShadow(QFrame.Raised) # frame.setMinimumWidth(430) # frame.setFixedHeight(395) frame.setStyleSheet("border: none") add_employee_button = QLabel(frame) add_employee_button.setAlignment(Qt.AlignCenter) add_employee_button.setGeometry(QRect(110, 30, 210, 41)) add_employee_button.setStyleSheet( "font: 75 12pt \"MS Shell Dlg 2\";\n" "background-color: rgb(30, 45, 66);\n" "color: rgb(255, 255, 255);") add_employee_button.setText("Add Product Details") namelabel = QLabel(frame) namelabel.setText("Name") namelabel.setGeometry(QRect(70, 100, 47, 13)) nametextbox = QLineEdit(frame) nametextbox.setGeometry(QRect(160, 90, 181, 31)) nametextbox.setFixedWidth(180) categorylabel = QLabel(frame) categorylabel.setText("Category") categorylabel.setGeometry(QRect(70, 140, 61, 16)) categorytextbox = QComboBox(frame) categorytextbox.setGeometry(QRect(160, 130, 181, 31)) categorytextbox.setFixedWidth(180) categorytextbox.addItems(["Pizza", "Burger"]) quantitylabel = QLabel(frame) quantitylabel.setText("Quantity") quantitylabel.setGeometry(QRect(70, 180, 47, 13)) quantitytextbox = QLineEdit(frame) quantitytextbox.setGeometry(QRect(160, 170, 181, 31)) quantitytextbox.setFixedWidth(180) pricelabel = QLabel(frame) pricelabel.setText("Price") pricelabel.setGeometry(QRect(70, 220, 47, 13)) pricetextbox = QLineEdit(frame) pricetextbox.setGeometry(QRect(160, 210, 181, 31)) pricetextbox.setFixedWidth(180) sellingpricelabel = QLabel(frame) sellingpricelabel.setText("Selling Price") sellingpricelabel.setGeometry(QRect(70, 260, 90, 16)) sellingpricetextbox = QDateEdit(frame) sellingpricetextbox.setGeometry(QRect(160, 250, 181, 31)) sellingpricetextbox.setFixedWidth(180) sellingpricetextbox.setDate(QDate.currentDate()) sellingpricetextbox.setMinimumDate(QDate.currentDate()) addbutton = QPushButton(frame) addbutton.setText("Add Product") addbutton.setGeometry(QRect(160, 300, 111, 31)) addbutton.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";\n" "background-color: rgb(30, 45, 66);\n" "color: rgb(255, 255, 255);") layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(frame) self.setLayout(layout) self.setWindowTitle("Add Employee Details") self.resize(430, 395) self.show() self.center()
class AppStimed(QWidget): def __init__(self, parent=None): super().__init__(parent) #memanggil beberapa fungsi self.tableModel() self.groupBoxOther() self.txtAction() self.btnAction() self.gridLayout1() self.gridLayout2() self.gridLayout3() self.verticalLay() self.setWindowTitle("Data Mahasiswa STIMED Nusa Palapa") self.setGeometry(340, 50, 658, 650) self.setWindowIcon(QIcon("folderIcon/memed.png")) def tableModel(self): self.table = QTableWidget(0, 6) self.table.setHorizontalHeaderLabels( ['Nim', 'Nama', 'Jurusan', 'Tahun Masuk', 'Alamat', 'Agama']) self.table.setEditTriggers( QTableWidget.NoEditTriggers) #nonaktifkan untuk edit di tabel self.table.setSelectionBehavior( QTableWidget.SelectRows) #agar semua 1 baris terseleksi def groupBoxOther(self): self.groupBoxJrsn = QGroupBox(" [ Pilih Jurusan ] ", self) self.groupBoxForm = QGroupBox(" [ Isi Form ] ", self) self.groupBoxBtn = QGroupBox(" [ Tekan Tombol Berikut ] ", self) self.groupBoxCari = QGroupBox(" [ Search && Order ] ", self) self.radio1 = QRadioButton("TI (S1)", self.groupBoxJrsn) self.radio1.setGeometry(10, 20, 110, 20) self.radio2 = QRadioButton("SI (S1)", self.groupBoxJrsn) self.radio2.setGeometry(10, 40, 110, 20) self.radio1.toggled.connect(self.radio1Checked) self.radio2.toggled.connect(self.radio2Checked) self.lineV = QFrame(self.groupBoxJrsn) self.lineV.setGeometry(200, 10, 20, 50) self.lineV.setFrameShape(QFrame.VLine) self.lineV.setFrameShadow(QFrame.Sunken) def txtAction(self): self.lblNim = QLabel("Nim :") self.txtNim = QLineEdit() self.txtNim.setPlaceholderText("ex : 01510002 - tekan tombol help") self.txtNim.setMaxLength(8) self.lblNama = QLabel("Nama :") self.txtNama = QLineEdit() self.txtNama.setPlaceholderText("ex : imo") self.lblTahun = QLabel("Tahun Masuk : ") self.txtTahun = QLineEdit() self.txtTahun.setPlaceholderText("ex : 2015") self.txtTahun.setMaxLength(4) self.lblAlamat = QLabel("Alamat :") self.txtAlamat = QLineEdit() self.txtAlamat.setPlaceholderText("ex : Jl. Budidaya, Antang") self.lblAgama = QLabel("Agama :") self.txtAgama = QLineEdit() self.txtAgama.setPlaceholderText("ex : Islam") self.lblCari = QLabel("Cari Nama :", self.groupBoxCari) self.lblCari.setGeometry(10, 20, 100, 10) self.txtCari = QLineEdit() self.txtCari.setPlaceholderText("ex : Rafika") self.lblOrder = QLabel("<u>Urutkan semua data secara Asc :</u>", self.groupBoxCari) self.lblKeterangan = QLabel("<u>Keterangan Jurusan</u> :", self.groupBoxJrsn) self.lblKeterangan.setGeometry(250, 10, 110, 13) self.lblJrsan = QLabel("", self.groupBoxJrsn) self.lblJrsan.setGeometry(250, 30, 110, 13) def btnAction(self): self.btnSimpan = QPushButton('&Simpan') self.btnSimpan.clicked.connect(self.simpanData) self.btnSimpan.clicked.connect(self.loadData) self.btnUpdate = QPushButton('&Update') self.btnUpdate.clicked.connect(self.updateData) self.btnUpdate.clicked.connect(self.loadData) self.btnEdit = QPushButton('&Edit') self.btnEdit.clicked.connect(self.editData) self.btnHapus = QPushButton('&Hapus') self.btnHapus.clicked.connect(self.hapusData) self.btnReset = QPushButton('&Reset') self.btnReset.clicked.connect(self.resetTxt) self.btnReset.clicked.connect(self.loadData) self.btnExit = QPushButton('&Exit') self.btnExit.clicked.connect(self.close) self.btnPrint = QPushButton('&Print') self.btnPrint.clicked.connect(self.printTable) self.information = QPushButton('&Help') self.information.clicked.connect(self.helpMeWoi) self.btnCari = QPushButton("Cari", self.groupBoxCari) self.btnCari.clicked.connect(self.cariData) self.btnOrderNamaAsc = QPushButton("Order by nama", self.groupBoxCari) self.btnOrderNamaAsc.clicked.connect(self.loadData) self.btnOrderNamaAsc.clicked.connect(self.orderNamaAsc) self.btnOrderThnAsc = QPushButton("Order by tahun masuk", self.groupBoxCari) self.btnOrderThnAsc.clicked.connect(self.loadData) self.btnOrderThnAsc.clicked.connect(self.orderThnAsc) def gridLayout1(self): #txt,jrsn,label self.grid = QGridLayout(self.groupBoxForm) self.grid.setContentsMargins(10, 10, 110, 10) self.grid.addWidget(self.lblNim, 0, 0) self.grid.addWidget(self.txtNim, 0, 1) self.grid.addWidget(self.lblNama, 1, 0) self.grid.addWidget(self.txtNama, 1, 1) self.grid.addWidget(self.groupBoxJrsn, 2, 1, 12, 1) self.grid.addWidget(self.lblTahun, 17, 0) self.grid.addWidget(self.txtTahun, 17, 1) self.grid.addWidget(self.lblAlamat, 18, 0) self.grid.addWidget(self.txtAlamat, 18, 1) self.grid.addWidget(self.lblAgama, 19, 0) self.grid.addWidget(self.txtAgama, 19, 1) def gridLayout2(self): #gboxCari self.grid2 = QGridLayout(self.groupBoxCari) self.grid2.setContentsMargins(110, 5, 110, 5) #margin kiri,atas, kanan, bawah self.grid2.addWidget(self.txtCari, 0, 0, 1, 0) #baris 0 kolom 0 sampai, kolom 1 self.grid2.addWidget(self.btnCari, 1, 0, 1, 0) self.grid2.addWidget(self.lblOrder, 2, 0, 1, 0) self.grid2.addWidget(self.btnOrderNamaAsc, 3, 0) self.grid2.addWidget(self.btnOrderThnAsc, 3, 1) def gridLayout3(self): #actionBtn self.grid3 = QGridLayout(self.groupBoxBtn) self.grid3.addWidget(self.btnSimpan, 0, 0) self.grid3.addWidget(self.btnHapus, 1, 0) self.grid3.addWidget(self.btnEdit, 0, 1) self.grid3.addWidget(self.btnUpdate, 1, 1) self.grid3.addWidget(self.btnPrint, 0, 2) self.grid3.addWidget(self.btnReset, 1, 2) self.grid3.addWidget(self.btnExit, 0, 3) self.grid3.addWidget(self.information, 1, 3) def verticalLay(self): self.vbx = QVBoxLayout() self.vbx.addWidget(self.groupBoxForm) self.vbx.addWidget(self.groupBoxCari) self.vbx.addWidget(self.groupBoxBtn) self.vbx.addWidget(self.table) self.setLayout(self.vbx) #membuat vbx sebagai Layout utama def radio1Checked(self, enable): if enable: self.lblJrsan.setText("Teknik Informatika") def radio2Checked(self, enable): if enable: self.lblJrsan.setText("Sistem Informasi") def cariData(self): print("ini cari") cariNama = self.txtCari.text() index = 0 query = QSqlQuery() query.exec_( "SELECT * FROM tbl_mahasiswa WHERE nama LIKE '%{0}%'".format( cariNama)) while query.next(): nimMhs = query.value(0) namaMhs = query.value(1) jrsMhs = query.value(2) thnMhs = query.value(3) alamatMhs = query.value(4) agamaMhs = query.value(5) self.table.setRowCount(index + 1) self.table.setItem(index, 0, QTableWidgetItem(str(nimMhs))) self.table.setItem(index, 1, QTableWidgetItem(namaMhs)) self.table.setItem(index, 2, QTableWidgetItem(jrsMhs)) self.table.setItem(index, 3, QTableWidgetItem(str(thnMhs))) self.table.setItem(index, 4, QTableWidgetItem(alamatMhs)) self.table.setItem(index, 5, QTableWidgetItem(agamaMhs)) index += 1 def loadData(self): index = 0 query = QSqlQuery() query.exec_("SELECT * FROM tbl_mahasiswa") while query.next(): nimMhs = query.value(0) namaMhs = query.value(1) jrsMhs = query.value(2) thnMhs = query.value(3) alamatMhs = query.value(4) agamaMhs = query.value(5) self.table.setRowCount(index + 1) self.table.setItem(index, 0, QTableWidgetItem(str(nimMhs))) self.table.setItem(index, 1, QTableWidgetItem(namaMhs)) self.table.setItem(index, 2, QTableWidgetItem(jrsMhs)) self.table.setItem(index, 3, QTableWidgetItem(str(thnMhs))) self.table.setItem(index, 4, QTableWidgetItem(alamatMhs)) self.table.setItem(index, 5, QTableWidgetItem(agamaMhs)) index += 1 def simpanData(self): try: nimMhs = self.txtNim.text() namaMhs = self.txtNama.text() jrsMhs = self.lblJrsan.text() thnMhs = int(self.txtTahun.text()) alamatMhs = self.txtAlamat.text() agamaMhs = self.txtAgama.text() query = QSqlQuery() query.exec_("INSERT INTO tbl_mahasiswa VALUES('{0}', '{1}', '{2}', {3}, '{4}', '{5}')".\ format(nimMhs, namaMhs, jrsMhs, thnMhs, alamatMhs, agamaMhs)) except ValueError: QMessageBox.critical( self, "Terjadi Error", "Coba periksa data yang anda input.\n" "Mungkin terjadi kesalahan padan penginputan\n\n" "Klik Yes untuk mencoba lagi.", QMessageBox.Yes) self.resetTxt() def editData(self): try: selected = self.table.currentIndex() if not selected.isValid() or len(self.table.selectedItems()) < 1: return print(not selected.isValid()) self.nimMhs = self.table.selectedItems()[0] namaMhs = self.table.selectedItems()[1] jrsMhs = self.table.selectedItems()[2] thnMhs = self.table.selectedItems()[3] alamatMhs = self.table.selectedItems()[4] agamaMhs = self.table.selectedItems()[5] self.txtNim.setText(str(self.nimMhs.text())) self.txtNama.setText(str(namaMhs.text())) self.lblJrsan.setText(str(jrsMhs.text())) self.txtTahun.setText(str(thnMhs.text())) self.txtAlamat.setText(str(alamatMhs.text())) self.txtAgama.setText(str(agamaMhs.text())) except ValueError: print(ValueError) def updateData(self): try: namaMhs = self.txtNama.text() jrsMhs = self.lblJrsan.text() thnMhs = int(self.txtTahun.text()) alamatMhs = self.txtAlamat.text() agamaMhs = self.txtAgama.text() query = QSqlQuery() query.exec_("UPDATE tbl_mahasiswa SET nama='{0}', jurusan='{1}', thn_masuk={2},\ alamat='{3}', agama='{4}' WHERE nim='{5}'"\ .format(namaMhs, jrsMhs, thnMhs, alamatMhs, agamaMhs,self.nimMhs.text())) except ValueError: QMessageBox.critical( self, "Update Gagal", "Coba periksa data yang anda input.\n" "Mungkin terjadi kesalahan pada penginputan\n\n" "Klik Yes untuk mencoba lagi.", QMessageBox.Yes) self.resetTxt() def hapusData(self): selected = self.table.currentIndex() if not selected.isValid() or len(self.table.selectedItems()) < 1: return nimMhs = self.table.selectedItems()[0] query = QSqlQuery() try: query.exec_("delete from tbl_mahasiswa where nim = " + nimMhs.text()) except ValueError: QMessageBox.critical( self, "Hapus Gagal", "Coba periksa data Table\n\n" "Klik Yes untuk mencoba lagi.", QMessageBox.Yes) self.table.removeRow(selected.row()) self.table.setCurrentIndex(QModelIndex()) def resetTxt(self): self.txtNim.clear() self.txtNama.clear() self.txtTahun.clear() self.txtAlamat.clear() self.txtAgama.clear() self.txtCari.clear() def orderNamaAsc(self): index = 0 query = QSqlQuery() query.exec_("SELECT * FROM tbl_mahasiswa ORDER BY nama ASC") while query.next(): nimMhs = query.value(0) namaMhs = query.value(1) jrsMhs = query.value(2) thnMhs = query.value(3) alamatMhs = query.value(4) agamaMhs = query.value(5) self.table.setRowCount(index + 1) self.table.setItem(index, 0, QTableWidgetItem(str(nimMhs))) self.table.setItem(index, 1, QTableWidgetItem(namaMhs)) self.table.setItem(index, 2, QTableWidgetItem(jrsMhs)) self.table.setItem(index, 3, QTableWidgetItem(str(thnMhs))) self.table.setItem(index, 4, QTableWidgetItem(alamatMhs)) self.table.setItem(index, 5, QTableWidgetItem(agamaMhs)) index += 1 def orderThnAsc(self): index = 0 query = QSqlQuery() query.exec_("SELECT * FROM tbl_mahasiswa ORDER BY thn_masuk ASC") while query.next(): nimMhs = query.value(0) namaMhs = query.value(1) jrsMhs = query.value(2) thnMhs = query.value(3) alamatMhs = query.value(4) agamaMhs = query.value(5) self.table.setRowCount(index + 1) self.table.setItem(index, 0, QTableWidgetItem(str(nimMhs))) self.table.setItem(index, 1, QTableWidgetItem(namaMhs)) self.table.setItem(index, 2, QTableWidgetItem(jrsMhs)) self.table.setItem(index, 3, QTableWidgetItem(str(thnMhs))) self.table.setItem(index, 4, QTableWidgetItem(alamatMhs)) self.table.setItem(index, 5, QTableWidgetItem(agamaMhs)) index += 1 def closeEvent(self, event): reply = QMessageBox.question(self, 'Message', "Yakin ingin keluar ? ", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore() def printTable(self): printer = QPrinter(QPrinter.ScreenResolution) dlg = QPrintPreviewDialog(printer) view = PrintView() view.setModel(self.table.model()) dlg.paintRequested.connect(view.printIni) dlg.exec_() def helpMeWoi(self): QMessageBox.information(self,"Butuh Bantuan ka kodong :V","<b>PETUNJUK ! ** <br/>I HAVE NEW RULES CIKA :V</b><br/><br/><br/>"\ "<i><b>IKUTI ATURANKU NAH :</b><br/><br/>" "1. Penulisan nim masih belum bisa diawali dengan 0, karena tipe data Int<br/>" "bila diubah ke Varchar maka database pada aplikasi tidak dapat terhapus<br/>" "mungkin ada cara, but we, '<u>not found</u>' -,-<br/><br/>" "2. Untuk update data, pilih terlebih dahulu data pada tabel setelah itu tekan<br/>" "tombol edit dan akan muncul data yang terpilih dan tekan update jika selesai.<br/><br/>" "3. Saat ini nim tidak dapat di update karena nim sebagai PrimaryKey<br/>" "mungkin ada cara tapi kami belum menemukan source cara update PrimaryKey.<br/><br/><br/>" "<i>Create on 08/02/2018,</i><br/>" "<b>Created by: V:<b>") def db_connect(self, filename, server): db = QSqlDatabase.addDatabase(server) db.setDatabaseName(filename) ok = db.open() if not ok: QMessageBox.critical( self, "Tidak dapat membuka database", "Tidak dapat" "terhubung ke database.\n" "Cari di google tentang SQLite support. Baca tentang QtSQL" "\n\n\nKlik Ok untuk keluar.", QMessageBox.Ok) sys.exit() def db_create(self): query = QSqlQuery() query.exec_( "CREATE TABLE tbl_mahasiswa(nim VARCHAR(8) PRIMARY KEY," "nama VARCHAR(20) NOT NULL, jurusan VARCHAR(15) NOT NULL, thn_masuk int, alamat VARCHAR(30) NOT NULL,\ agama VARCHAR(20) NOT NULL)") query.exec_( "insert into tbl_mahasiswa values('01510002', 'Rafika Ramayanti', 'Sistem Informasi', 2015,\ 'Jl. Budidaya, antang', 'Islam')") def init(self, filename, server): import os if not os.path.exists(filename): self.db_connect(filename, server) self.db_create() else: self.db_connect(filename, server)
def __makeHorizontalLine(self): hLine = QFrame() hLine.setFrameShape(QFrame.HLine) hLine.setFrameShadow(QFrame.Sunken) return hLine
def add_h_line(self): line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) return line
class MainWindow_Ui(QMainWindow): def __init__(self, persepolis_setting): super().__init__() # MainWindow self.persepolis_setting = persepolis_setting # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # set ui direction ui_direction = self.persepolis_setting.value('ui_direction') if ui_direction == 'rtl': self.setLayoutDirection(Qt.RightToLeft) elif ui_direction in 'ltr': self.setLayoutDirection(Qt.LeftToRight) icons = ':/' + \ str(self.persepolis_setting.value('settings/icons')) + '/' self.setWindowTitle(QCoreApplication.translate("mainwindow_ui_tr", "Persepolis Download Manager")) self.setWindowIcon(QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg'))) self.centralwidget = QWidget(self) self.verticalLayout = QVBoxLayout(self.centralwidget) # enable drag and drop self.setAcceptDrops(True) # frame self.frame = QFrame(self.centralwidget) # download_table_horizontalLayout download_table_horizontalLayout = QHBoxLayout() tabels_splitter = QSplitter(Qt.Horizontal) # category_tree self.category_tree_qwidget = QWidget(self) category_tree_verticalLayout = QVBoxLayout() self.category_tree = CategoryTreeView(self) category_tree_verticalLayout.addWidget(self.category_tree) self.category_tree_model = QStandardItemModel() self.category_tree.setModel(self.category_tree_model) category_table_header = [QCoreApplication.translate("mainwindow_ui_tr", 'Category')] self.category_tree_model.setHorizontalHeaderLabels( category_table_header) self.category_tree.header().setStretchLastSection(True) self.category_tree.header().setDefaultAlignment(Qt.AlignCenter) # queue_panel self.queue_panel_widget = QWidget(self) queue_panel_verticalLayout_main = QVBoxLayout(self.queue_panel_widget) # queue_panel_show_button self.queue_panel_show_button = QPushButton(self) queue_panel_verticalLayout_main.addWidget(self.queue_panel_show_button) # queue_panel_widget_frame self.queue_panel_widget_frame = QFrame(self) self.queue_panel_widget_frame.setFrameShape(QFrame.StyledPanel) self.queue_panel_widget_frame.setFrameShadow(QFrame.Raised) queue_panel_verticalLayout_main.addWidget( self.queue_panel_widget_frame) queue_panel_verticalLayout = QVBoxLayout(self.queue_panel_widget_frame) queue_panel_verticalLayout_main.setContentsMargins(50, -1, 50, -1) # start_end_frame self.start_end_frame = QFrame(self) # start time start_verticalLayout = QVBoxLayout(self.start_end_frame) self.start_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.start_checkBox) self.start_frame = QFrame(self) self.start_frame.setFrameShape(QFrame.StyledPanel) self.start_frame.setFrameShadow(QFrame.Raised) start_frame_verticalLayout = QVBoxLayout(self.start_frame) self.start_time_qDataTimeEdit = QDateTimeEdit(self.start_frame) self.start_time_qDataTimeEdit.setDisplayFormat('H:mm') start_frame_verticalLayout.addWidget(self.start_time_qDataTimeEdit) start_verticalLayout.addWidget(self.start_frame) # end time self.end_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.end_checkBox) self.end_frame = QFrame(self) self.end_frame.setFrameShape(QFrame.StyledPanel) self.end_frame.setFrameShadow(QFrame.Raised) end_frame_verticalLayout = QVBoxLayout(self.end_frame) self.end_time_qDateTimeEdit = QDateTimeEdit(self.end_frame) self.end_time_qDateTimeEdit.setDisplayFormat('H:mm') end_frame_verticalLayout.addWidget(self.end_time_qDateTimeEdit) start_verticalLayout.addWidget(self.end_frame) self.reverse_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.reverse_checkBox) queue_panel_verticalLayout.addWidget(self.start_end_frame) # limit_after_frame self.limit_after_frame = QFrame(self) # limit_checkBox limit_verticalLayout = QVBoxLayout(self.limit_after_frame) self.limit_checkBox = QCheckBox(self) limit_verticalLayout.addWidget(self.limit_checkBox) # limit_frame self.limit_frame = QFrame(self) self.limit_frame.setFrameShape(QFrame.StyledPanel) self.limit_frame.setFrameShadow(QFrame.Raised) limit_verticalLayout.addWidget(self.limit_frame) limit_frame_verticalLayout = QVBoxLayout(self.limit_frame) # limit_spinBox limit_frame_horizontalLayout = QHBoxLayout() self.limit_spinBox = QDoubleSpinBox(self) self.limit_spinBox.setMinimum(1) self.limit_spinBox.setMaximum(1023) limit_frame_horizontalLayout.addWidget(self.limit_spinBox) # limit_comboBox self.limit_comboBox = QComboBox(self) self.limit_comboBox.addItem("") self.limit_comboBox.addItem("") limit_frame_horizontalLayout.addWidget(self.limit_comboBox) limit_frame_verticalLayout.addLayout(limit_frame_horizontalLayout) # limit_pushButton self.limit_pushButton = QPushButton(self) limit_frame_verticalLayout.addWidget(self.limit_pushButton) # after_checkBox self.after_checkBox = QtWidgets.QCheckBox(self) limit_verticalLayout.addWidget(self.after_checkBox) # after_frame self.after_frame = QtWidgets.QFrame(self) self.after_frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.after_frame.setFrameShadow(QtWidgets.QFrame.Raised) limit_verticalLayout.addWidget(self.after_frame) after_frame_verticalLayout = QVBoxLayout(self.after_frame) # after_comboBox self.after_comboBox = QComboBox(self) self.after_comboBox.addItem("") after_frame_verticalLayout.addWidget(self.after_comboBox) # after_pushButton self.after_pushButton = QPushButton(self) after_frame_verticalLayout.addWidget(self.after_pushButton) queue_panel_verticalLayout.addWidget(self.limit_after_frame) category_tree_verticalLayout.addWidget(self.queue_panel_widget) # keep_awake_checkBox self.keep_awake_checkBox = QCheckBox(self) queue_panel_verticalLayout.addWidget(self.keep_awake_checkBox) self.category_tree_qwidget.setLayout(category_tree_verticalLayout) tabels_splitter.addWidget(self.category_tree_qwidget) # download table widget self.download_table_content_widget = QWidget(self) download_table_content_widget_verticalLayout = QVBoxLayout( self.download_table_content_widget) self.download_table = DownloadTableWidget(self) download_table_content_widget_verticalLayout.addWidget( self.download_table) tabels_splitter.addWidget(self.download_table_content_widget) self.download_table.setColumnCount(13) self.download_table.setSelectionBehavior(QAbstractItemView.SelectRows) self.download_table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.download_table.verticalHeader().hide() # hide gid and download dictioanry section self.download_table.setColumnHidden(8, True) self.download_table.setColumnHidden(9, True) download_table_header = [QCoreApplication.translate("mainwindow_ui_tr", 'File Name'), QCoreApplication.translate("mainwindow_ui_tr",'Status'), QCoreApplication.translate("mainwindow_ui_tr", 'Size'), QCoreApplication.translate("mainwindow_ui_tr", 'Downloaded'), QCoreApplication.translate("mainwindow_ui_tr", 'Percentage'), QCoreApplication.translate("mainwindow_ui_tr", 'Connections'), QCoreApplication.translate("mainwindow_ui_tr", 'Transfer rate'), QCoreApplication.translate("mainwindow_ui_tr",'Estimated time left'), 'Gid', QCoreApplication.translate("mainwindow_ui_tr",'Link'), QCoreApplication.translate("mainwindow_ui_tr", 'First try date'), QCoreApplication.translate("mainwindow_ui_tr", 'Last try date'), QCoreApplication.translate("mainwindow_ui_tr",'Category')] self.download_table.setHorizontalHeaderLabels(download_table_header) # fixing the size of download_table when window is Maximized! self.download_table.horizontalHeader().setSectionResizeMode(0) self.download_table.horizontalHeader().setStretchLastSection(True) tabels_splitter.setStretchFactor(0, 3) # category_tree width tabels_splitter.setStretchFactor(1, 10) # ratio of tables's width download_table_horizontalLayout.addWidget(tabels_splitter) self.frame.setLayout(download_table_horizontalLayout) self.verticalLayout.addWidget(self.frame) self.setCentralWidget(self.centralwidget) # menubar self.menubar = QMenuBar(self) self.menubar.setGeometry(QRect(0, 0, 600, 24)) self.setMenuBar(self.menubar) fileMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&File')) editMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&Edit')) viewMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&View')) downloadMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&Download')) queueMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&Queue')) videoFinderMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", 'V&ideo Finder')) helpMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&Help')) # viewMenu submenus sortMenu = viewMenu.addMenu(QCoreApplication.translate("mainwindow_ui_tr", 'Sort by')) # statusbar self.statusbar = QStatusBar(self) self.setStatusBar(self.statusbar) self.statusbar.showMessage(QCoreApplication.translate("mainwindow_ui_tr", "Persepolis Download Manager")) # toolBar self.toolBar2 = QToolBar(self) self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar2) self.toolBar2.setWindowTitle(QCoreApplication.translate("mainwindow_ui_tr", 'Menu')) self.toolBar2.setFloatable(False) self.toolBar2.setMovable(False) self.toolBar = QToolBar(self) self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar) self.toolBar.setWindowTitle(QCoreApplication.translate("mainwindow_ui_tr", 'Toolbar')) self.toolBar.setFloatable(False) self.toolBar.setMovable(False) #toolBar and menubar and actions self.persepolis_setting.beginGroup('settings/shortcuts') # videoFinderAddLinkAction self.videoFinderAddLinkAction = QAction(QIcon(icons + 'video_finder'), QCoreApplication.translate("mainwindow_ui_tr", 'Find Video Links'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Download video or audio from Youtube, Vimeo, etc...'), triggered=self.showVideoFinderAddLinkWindow) self.videoFinderAddLinkAction_shortcut = QShortcut(self.persepolis_setting.value('video_finder_shortcut'), self, self.showVideoFinderAddLinkWindow) videoFinderMenu.addAction(self.videoFinderAddLinkAction) # stopAllAction self.stopAllAction = QAction(QIcon(icons + 'stop_all'), QCoreApplication.translate("mainwindow_ui_tr", 'Stop all active downloads'), self, statusTip='Stop all active downloads', triggered=self.stopAllDownloads) downloadMenu.addAction(self.stopAllAction) # sort_file_name_Action self.sort_file_name_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'File name'), self, triggered=self.sortByName) sortMenu.addAction(self.sort_file_name_Action) # sort_file_size_Action self.sort_file_size_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'File size'), self, triggered=self.sortBySize) sortMenu.addAction(self.sort_file_size_Action) # sort_first_try_date_Action self.sort_first_try_date_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'First try date'), self, triggered=self.sortByFirstTry) sortMenu.addAction(self.sort_first_try_date_Action) # sort_last_try_date_Action self.sort_last_try_date_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Last try date'), self, triggered=self.sortByLastTry) sortMenu.addAction(self.sort_last_try_date_Action) # sort_download_status_Action self.sort_download_status_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Download status'), self, triggered=self.sortByStatus) sortMenu.addAction(self.sort_download_status_Action) # trayAction self.trayAction = QAction(QCoreApplication.translate("mainwindow_ui_tr", 'Show system tray icon'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Show/Hide system tray icon"), triggered=self.showTray) self.trayAction.setCheckable(True) viewMenu.addAction(self.trayAction) # showMenuBarAction self.showMenuBarAction = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Show menubar'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Show menubar'), triggered=self.showMenuBar) self.showMenuBarAction.setCheckable(True) viewMenu.addAction(self.showMenuBarAction) # showSidePanelAction self.showSidePanelAction = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Show side panel'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Show side panel'), triggered=self.showSidePanel) self.showSidePanelAction.setCheckable(True) viewMenu.addAction(self.showSidePanelAction) # minimizeAction self.minimizeAction = QAction(QIcon(icons + 'minimize'), QCoreApplication.translate("mainwindow_ui_tr", 'Minimize to system tray'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Minimize to system tray"), triggered=self.minMaxTray) self.minimizeAction_shortcut = QShortcut(self.persepolis_setting.value('hide_window_shortcut'), self, self.minMaxTray) viewMenu.addAction(self.minimizeAction) # addlinkAction self.addlinkAction = QAction(QIcon(icons + 'add'), QCoreApplication.translate("mainwindow_ui_tr", 'Add New Download Link'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Add New Download Link"), triggered=self.addLinkButtonPressed) self.addlinkAction_shortcut = QShortcut(self.persepolis_setting.value('add_new_download_shortcut'), self, self.addLinkButtonPressed) fileMenu.addAction(self.addlinkAction) # importText self.addtextfileAction = QAction(QIcon(icons + 'file'), QCoreApplication.translate("mainwindow_ui_tr", 'Import links from text file'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Create a Text file and put links in it.line by line!'), triggered=self.importText) self.addtextfileAction_shortcut = QShortcut(self.persepolis_setting.value('import_text_shortcut'), self, self.importText) fileMenu.addAction(self.addtextfileAction) # resumeAction self.resumeAction = QAction(QIcon(icons + 'play'), QCoreApplication.translate("mainwindow_ui_tr", 'Resume Download'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Resume Download"), triggered=self.resumeButtonPressed) downloadMenu.addAction(self.resumeAction) # pauseAction self.pauseAction = QAction(QIcon(icons + 'pause'), QCoreApplication.translate("mainwindow_ui_tr", 'Pause Download'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Pause Download"), triggered=self.pauseButtonPressed) downloadMenu.addAction(self.pauseAction) # stopAction self.stopAction = QAction(QIcon(icons + 'stop'), QCoreApplication.translate("mainwindow_ui_tr", 'Stop Download'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Stop/Cancel Download"), triggered=self.stopButtonPressed) downloadMenu.addAction(self.stopAction) # propertiesAction self.propertiesAction = QAction(QIcon(icons + 'setting'), QCoreApplication.translate("mainwindow_ui_tr", 'Properties'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Properties"), triggered=self.propertiesButtonPressed) downloadMenu.addAction(self.propertiesAction) # progressAction self.progressAction = QAction(QIcon(icons + 'window'), QCoreApplication.translate("mainwindow_ui_tr", 'Progress'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Progress"), triggered=self.progressButtonPressed) downloadMenu.addAction(self.progressAction) # openFileAction self.openFileAction = QAction(QIcon( icons + 'file'), QCoreApplication.translate("mainwindow_ui_tr", 'Open file'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Open file'), triggered=self.openFile) fileMenu.addAction(self.openFileAction) # openDownloadFolderAction self.openDownloadFolderAction = QAction(QIcon( icons + 'folder'), QCoreApplication.translate("mainwindow_ui_tr", 'Open download folder'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Open download folder'), triggered=self.openDownloadFolder) fileMenu.addAction(self.openDownloadFolderAction) # openDefaultDownloadFolderAction self.openDefaultDownloadFolderAction = QAction(QIcon( icons + 'folder'), QCoreApplication.translate("mainwindow_ui_tr", 'Open default download folder'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Open default download folder'), triggered=self.openDefaultDownloadFolder) fileMenu.addAction(self.openDefaultDownloadFolderAction) # exitAction self.exitAction = QAction(QIcon(icons + 'exit'), QCoreApplication.translate("mainwindow_ui_tr", 'Exit'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Exit"), triggered=self.closeEvent) self.exitAction_shortcut = QShortcut(self.persepolis_setting.value('quit_shortcut'), self, self.closeEvent) fileMenu.addAction(self.exitAction) # clearAction self.clearAction = QAction(QIcon(icons + 'multi_remove'), QCoreApplication.translate("mainwindow_ui_tr", 'Clear download list'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Clear all items in download list'), triggered=self.clearDownloadList) editMenu.addAction(self.clearAction) # removeSelectedAction self.removeSelectedAction = QAction(QIcon(icons + 'remove'), QCoreApplication.translate("mainwindow_ui_tr", 'Remove selected downloads from list'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Remove selected downloads form list'), triggered=self.removeSelected) self.removeSelectedAction_shortcut = QShortcut(self.persepolis_setting.value('remove_shortcut'), self, self.removeSelected) editMenu.addAction(self.removeSelectedAction) self.removeSelectedAction.setEnabled(False) # deleteSelectedAction self.deleteSelectedAction = QAction(QIcon(icons + 'trash'), QCoreApplication.translate("mainwindow_ui_tr", 'Delete selected download files'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Delete selected download files'), triggered=self.deleteSelected) self.deleteSelectedAction_shortcut = QShortcut(self.persepolis_setting.value('delete_shortcut'), self, self.deleteSelected) editMenu.addAction(self.deleteSelectedAction) self.deleteSelectedAction.setEnabled(False) # createQueueAction self.createQueueAction = QAction(QIcon(icons + 'add_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Create new queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Create new download queue'), triggered=self.createQueue) queueMenu.addAction(self.createQueueAction) # removeQueueAction self.removeQueueAction = QAction(QIcon(icons + 'remove_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Remove this queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Remove this queue'), triggered=self.removeQueue) queueMenu.addAction(self.removeQueueAction) # startQueueAction self.startQueueAction = QAction(QIcon( icons + 'start_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Start this queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Start this queue'), triggered=self.startQueue) queueMenu.addAction(self.startQueueAction) # stopQueueAction self.stopQueueAction = QAction(QIcon( icons + 'stop_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Stop this queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Stop this queue'), triggered=self.stopQueue) queueMenu.addAction(self.stopQueueAction) # moveUpSelectedAction self.moveUpSelectedAction = QAction(QIcon(icons + 'multi_up'), QCoreApplication.translate("mainwindow_ui_tr", 'Move up selected items'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Move currently selected items up by one row'), triggered=self.moveUpSelected) self.moveUpSelectedAction_shortcut = QShortcut(self.persepolis_setting.value('move_up_selection_shortcut'), self, self.moveUpSelected) queueMenu.addAction(self.moveUpSelectedAction) # moveDownSelectedAction self.moveDownSelectedAction = QAction(QIcon(icons + 'multi_down'), QCoreApplication.translate("mainwindow_ui_tr", 'Move down selected items'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Move currently selected items down by one row'), triggered=self.moveDownSelected) self.moveDownSelectedAction_shortcut = QShortcut(self.persepolis_setting.value('move_down_selection_shortcut'), self, self.moveDownSelected) queueMenu.addAction(self.moveDownSelectedAction) # preferencesAction self.preferencesAction = QAction(QIcon(icons + 'preferences'), QCoreApplication.translate("mainwindow_ui_tr", 'Preferences'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Preferences'), triggered=self.openPreferences, menuRole=5) editMenu.addAction(self.preferencesAction) # aboutAction self.aboutAction = QAction(QIcon( icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'About'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'About'), triggered=self.openAbout, menuRole=4) helpMenu.addAction(self.aboutAction) # issueAction self.issueAction = QAction(QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Report an issue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Report an issue'), triggered=self.reportIssue) helpMenu.addAction(self.issueAction) # updateAction self.updateAction = QAction(QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Check for newer version'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Check for newer release'), triggered=self.newUpdate) helpMenu.addAction(self.updateAction) # logAction self.logAction = QAction(QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Show log file'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Help'), triggered=self.showLog) helpMenu.addAction(self.logAction) # helpAction self.helpAction = QAction(QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Help'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Help'), triggered=self.persepolisHelp) helpMenu.addAction(self.helpAction) self.persepolis_setting.endGroup() self.qmenu = MenuWidget(self) self.toolBar2.addWidget(self.qmenu) # labels self.queue_panel_show_button.setText(QCoreApplication.translate("mainwindow_ui_tr", "Hide options")) self.start_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "Start Time")) self.end_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "End Time")) self.reverse_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "Download bottom of\n the list first")) self.limit_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "Limit Speed")) self.limit_comboBox.setItemText(0, "KiB/s") self.limit_comboBox.setItemText(1, "MiB/s") self.limit_pushButton.setText(QCoreApplication.translate("mainwindow_ui_tr", "Apply")) self.after_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "After download")) self.after_comboBox.setItemText(0, QCoreApplication.translate("mainwindow_ui_tr", "Shut Down")) self.keep_awake_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "Keep system awake!")) self.keep_awake_checkBox.setToolTip( QCoreApplication.translate("mainwindow_ui_tr", "<html><head/><body><p>This option is preventing system from going to sleep.\ This is necessary if your power manager is suspending system automatically. </p></body></html>")) self.after_pushButton.setText(QCoreApplication.translate("mainwindow_ui_tr", "Apply")) def changeIcon(self, icons): icons = ':/' + str(icons) + '/' action_icon_dict = {self.stopAllAction: 'stop_all', self.minimizeAction: 'minimize', self.addlinkAction: 'add', self.addtextfileAction: 'file', self.resumeAction: 'play', self.pauseAction: 'pause', self.stopAction: 'stop', self.propertiesAction: 'setting', self.progressAction: 'window', self.openFileAction: 'file', self.openDownloadFolderAction: 'folder', self.openDefaultDownloadFolderAction: 'folder', self.exitAction: 'exit', self.removeSelectedAction: 'multi_remove', self.deleteSelectedAction: 'multi_trash', self.createQueueAction: 'add_queue', self.removeQueueAction: 'remove_queue', self.startQueueAction: 'start_queue', self.stopQueueAction: 'stop_queue', self.preferencesAction: 'preferences', self.aboutAction: 'about', self.issueAction: 'about', self.updateAction: 'about', self.videoFinderAddLinkAction: 'video_finder', self.qmenu: 'menu'} for key in action_icon_dict.keys(): key.setIcon(QIcon(icons + str(action_icon_dict[key])))
class LogicViewTopBar(QWidget): def __init__(self): super().__init__() self._canCopy = True self._entityLogic = None self._frame = QFrame() self._frame.setFrameStyle(QFrame.StyledPanel) self._frame.setFrameShadow(QFrame.Plain) self._frameLayout = QHBoxLayout() self._frameLayout.setSpacing(1) self._frameLayout.setContentsMargins(0, 0, 0, 0) self._frame.setContextMenuPolicy(Qt.CustomContextMenu) self._frame.customContextMenuRequested.connect( self._signal_frame_contexMenuRequested) self._expandLogicBt = QPushButton() self._expandLogicBt.setIcon(self.style().standardIcon( QStyle.SP_TitleBarShadeButton)) self._expandLogicBt.setFlat(True) self._frameLayout.addWidget(self._expandLogicBt) self._logicNameLabel = QLabel() self._frameLayout.addWidget(self._logicNameLabel) self._frameLayout.addStretch() self._removeLogicBt = QPushButton() self._removeLogicBt.setIcon(self.style().standardIcon( QStyle.SP_TitleBarCloseButton)) self._removeLogicBt.setFlat(True) self._removeLogicBt.clicked.connect(self._signal_removeBt_clicked) self._frameLayout.addWidget(self._removeLogicBt) self._frame.setLayout(self._frameLayout) self._rootLayout = QVBoxLayout() self._rootLayout.setSpacing(0) self._rootLayout.setContentsMargins(0, 0, 0, 0) self._rootLayout.addWidget(self._frame) self.setLayout(self._rootLayout) def _setupLogic(self, entityLogic): self._entityLogic = entityLogic self._logicNameLabel.setText(self._entityLogic.getName()) def _setCanCopy(self, copyFlag): self._canCopy = copyFlag def _signal_removeBt_clicked(self): GetEventManager().onRemoveEntityLogicBtClicked(self._entityLogic) def _signal_frame_contexMenuRequested(self, pt): if not self._canCopy: return menu = EntityLogicMenu(self) globalPt = self._frame.mapToGlobal(pt) menu.onMenuRequestedOnLogic(globalPt, self._entityLogic)
class Setting_Ui(QWidget): def __init__(self, persepolis_setting): super().__init__() icon = QtGui.QIcon() self.setWindowIcon(QIcon.fromTheme('persepolis', QIcon(':/icon.svg'))) self.setWindowTitle('Preferences') global icons icons = ':/' + str(persepolis_setting.value('settings/icons')) + '/' self.verticalLayout_2 = QVBoxLayout(self) self.setting_tabWidget = QTabWidget(self) # download_options_tab self.download_options_tab = QWidget() self.layoutWidget = QWidget(self.download_options_tab) self.download_options_verticalLayout = QVBoxLayout(self.layoutWidget) self.download_options_verticalLayout.setContentsMargins(21, 21, 0, 0) self.download_options_verticalLayout.setObjectName( "download_options_verticalLayout") self.horizontalLayout_5 = QHBoxLayout() # tries_label self.tries_label = QLabel(self.layoutWidget) self.horizontalLayout_5.addWidget(self.tries_label) # tries_spinBox self.tries_spinBox = QSpinBox(self.layoutWidget) self.tries_spinBox.setMinimum(1) self.horizontalLayout_5.addWidget(self.tries_spinBox) self.download_options_verticalLayout.addLayout(self.horizontalLayout_5) self.horizontalLayout_4 = QHBoxLayout() # wait_label self.wait_label = QLabel(self.layoutWidget) self.horizontalLayout_4.addWidget(self.wait_label) # wait_spinBox self.wait_spinBox = QSpinBox(self.layoutWidget) self.horizontalLayout_4.addWidget(self.wait_spinBox) self.download_options_verticalLayout.addLayout(self.horizontalLayout_4) self.horizontalLayout_3 = QHBoxLayout() # time_out_label self.time_out_label = QLabel(self.layoutWidget) self.horizontalLayout_3.addWidget(self.time_out_label) # time_out_spinBox self.time_out_spinBox = QSpinBox(self.layoutWidget) self.horizontalLayout_3.addWidget(self.time_out_spinBox) self.download_options_verticalLayout.addLayout(self.horizontalLayout_3) self.horizontalLayout_2 = QHBoxLayout() # connections_label self.connections_label = QLabel(self.layoutWidget) self.horizontalLayout_2.addWidget(self.connections_label) # connections_spinBox self.connections_spinBox = QSpinBox(self.layoutWidget) self.connections_spinBox.setMinimum(1) self.connections_spinBox.setMaximum(16) self.horizontalLayout_2.addWidget(self.connections_spinBox) self.download_options_verticalLayout.addLayout(self.horizontalLayout_2) # rpc_port_label self.rpc_port_label = QLabel(self.layoutWidget) self.rpc_horizontalLayout = QHBoxLayout() self.rpc_horizontalLayout.addWidget(self.rpc_port_label) # rpc_port_spinbox self.rpc_port_spinbox = QSpinBox(self.layoutWidget) self.rpc_port_spinbox.setMinimum(1024) self.rpc_port_spinbox.setMaximum(65535) self.rpc_horizontalLayout.addWidget(self.rpc_port_spinbox) self.download_options_verticalLayout.addLayout( self.rpc_horizontalLayout) self.setting_tabWidget.addTab(self.download_options_tab, "") # save_as_tab self.save_as_tab = QWidget() self.layoutWidget1 = QWidget(self.save_as_tab) self.save_as_verticalLayout = QVBoxLayout(self.layoutWidget1) self.save_as_verticalLayout.setContentsMargins(20, 30, 0, 0) self.download_folder_horizontalLayout = QHBoxLayout() # download_folder_label self.download_folder_label = QLabel(self.layoutWidget1) self.download_folder_horizontalLayout.addWidget( self.download_folder_label) # download_folder_lineEdit self.download_folder_lineEdit = QLineEdit(self.layoutWidget1) self.download_folder_horizontalLayout.addWidget( self.download_folder_lineEdit) # download_folder_pushButton self.download_folder_pushButton = QPushButton(self.layoutWidget1) self.download_folder_horizontalLayout.addWidget( self.download_folder_pushButton) self.save_as_verticalLayout.addLayout( self.download_folder_horizontalLayout) self.temp_horizontalLayout = QHBoxLayout() # temp_download_label self.temp_download_label = QLabel(self.layoutWidget1) self.temp_horizontalLayout.addWidget(self.temp_download_label) # temp_download_lineEdit self.temp_download_lineEdit = QLineEdit(self.layoutWidget1) self.temp_horizontalLayout.addWidget(self.temp_download_lineEdit) # temp_download_pushButton self.temp_download_pushButton = QPushButton(self.layoutWidget1) self.temp_horizontalLayout.addWidget(self.temp_download_pushButton) self.save_as_verticalLayout.addLayout(self.temp_horizontalLayout) self.setting_tabWidget.addTab(self.save_as_tab, "") # notifications_tab self.notifications_tab = QWidget() self.layoutWidget2 = QWidget(self.notifications_tab) self.verticalLayout_4 = QVBoxLayout(self.layoutWidget2) self.verticalLayout_4.setContentsMargins(21, 21, 0, 0) # enable_notifications_checkBox self.enable_notifications_checkBox = QCheckBox(self.layoutWidget2) self.verticalLayout_4.addWidget(self.enable_notifications_checkBox) # sound_frame self.sound_frame = QFrame(self.layoutWidget2) self.sound_frame.setFrameShape(QFrame.StyledPanel) self.sound_frame.setFrameShadow(QFrame.Raised) self.verticalLayout = QVBoxLayout(self.sound_frame) # volume_label self.volume_label = QLabel(self.sound_frame) self.verticalLayout.addWidget(self.volume_label) # volume_dial self.volume_dial = QDial(self.sound_frame) self.volume_dial.setProperty("value", 100) self.verticalLayout.addWidget(self.volume_dial) self.verticalLayout_4.addWidget(self.sound_frame) self.setting_tabWidget.addTab(self.notifications_tab, "") # style_tab self.style_tab = QWidget() self.layoutWidget3 = QWidget(self.style_tab) self.verticalLayout_3 = QVBoxLayout(self.layoutWidget3) self.verticalLayout_3.setContentsMargins(21, 21, 0, 0) self.horizontalLayout_8 = QHBoxLayout() # style_label self.style_label = QLabel(self.layoutWidget3) self.horizontalLayout_8.addWidget(self.style_label) # style_comboBox self.style_comboBox = QComboBox(self.layoutWidget3) self.horizontalLayout_8.addWidget(self.style_comboBox) self.verticalLayout_3.addLayout(self.horizontalLayout_8) self.horizontalLayout_7 = QHBoxLayout() # color_label self.color_label = QLabel(self.layoutWidget3) self.horizontalLayout_7.addWidget(self.color_label) # color_comboBox self.color_comboBox = QComboBox(self.layoutWidget3) self.horizontalLayout_7.addWidget(self.color_comboBox) self.verticalLayout_3.addLayout(self.horizontalLayout_7) # icon_label self.horizontalLayout_12 = QHBoxLayout() self.icon_label = QLabel(self.layoutWidget3) self.horizontalLayout_12.addWidget(self.icon_label) # icon_comboBox self.icon_comboBox = QComboBox(self.layoutWidget3) self.horizontalLayout_12.addWidget(self.icon_comboBox) self.verticalLayout_3.addLayout(self.horizontalLayout_12) self.horizontalLayout_6 = QHBoxLayout() # notification_label self.horizontalLayout_13 = QHBoxLayout() self.notification_label = QLabel(self.layoutWidget3) self.horizontalLayout_13.addWidget(self.notification_label) # notification_comboBox self.notification_comboBox = QComboBox(self.layoutWidget3) self.horizontalLayout_13.addWidget(self.notification_comboBox) self.verticalLayout_3.addLayout(self.horizontalLayout_13) # font_label self.font_label = QLabel(self.layoutWidget3) self.horizontalLayout_6.addWidget(self.font_label) # fontComboBox self.fontComboBox = QFontComboBox(self.layoutWidget3) self.horizontalLayout_6.addWidget(self.fontComboBox) # font_size_label self.font_size_label = QLabel(self.layoutWidget3) self.horizontalLayout_6.addWidget(self.font_size_label) # font_size_spinBox self.font_size_spinBox = QSpinBox(self.layoutWidget3) self.font_size_spinBox.setMinimum(1) self.horizontalLayout_6.addWidget(self.font_size_spinBox) self.verticalLayout_3.addLayout(self.horizontalLayout_6) self.setting_tabWidget.addTab(self.style_tab, "") self.verticalLayout_2.addWidget(self.setting_tabWidget) self.horizontalLayout = QHBoxLayout() spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) # Enable system tray icon self.enable_system_tray_checkBox = QCheckBox(self.layoutWidget3) self.verticalLayout_3.addWidget(self.enable_system_tray_checkBox) # after_download dialog self.after_download_checkBox = QCheckBox() self.verticalLayout_3.addWidget(self.after_download_checkBox) # show_menubar_checkbox self.show_menubar_checkbox = QCheckBox() self.verticalLayout_3.addWidget(self.show_menubar_checkbox) # show_sidepanel_checkbox self.show_sidepanel_checkbox = QCheckBox() self.verticalLayout_3.addWidget(self.show_sidepanel_checkbox) # hide progress window self.show_progress_window_checkbox = QCheckBox() self.verticalLayout_3.addWidget(self.show_progress_window_checkbox) # add persepolis to startup self.startup_checkbox = QCheckBox() self.verticalLayout_3.addWidget(self.startup_checkbox) # defaults_pushButton self.defaults_pushButton = QPushButton(self) self.horizontalLayout.addWidget(self.defaults_pushButton) # cancel_pushButton self.cancel_pushButton = QPushButton(self) self.cancel_pushButton.setIcon(QIcon(icons + 'remove')) self.horizontalLayout.addWidget(self.cancel_pushButton) # ok_pushButton self.ok_pushButton = QPushButton(self) self.ok_pushButton.setIcon(QIcon(icons + 'ok')) self.horizontalLayout.addWidget(self.ok_pushButton) self.verticalLayout_2.addLayout(self.horizontalLayout) self.setting_tabWidget.setCurrentIndex(3) self.setWindowTitle("Preferences") self.tries_label.setToolTip( "<html><head/><body><p>Set number of tries if download failed.</p></body></html>" ) self.tries_label.setText("Number of tries : ") self.tries_spinBox.setToolTip( "<html><head/><body><p>Set number of tries if download failed.</p></body></html>" ) self.wait_label.setToolTip( "<html><head/><body><p>Set the seconds to wait between retries. Download manager will retry downloads when the HTTP server returns a 503 response.</p></body></html>" ) self.wait_label.setText("Wait between retries (seconds) : ") self.wait_spinBox.setToolTip( "<html><head/><body><p>Set the seconds to wait between retries. Download manager will retry downloads when the HTTP server returns a 503 response.</p></body></html>" ) self.time_out_label.setToolTip( "<html><head/><body><p>Set timeout in seconds. </p></body></html>") self.time_out_label.setText("Time out (seconds) : ") self.time_out_spinBox.setToolTip( "<html><head/><body><p>Set timeout in seconds. </p></body></html>") self.connections_label.setToolTip( "<html><head/><body><p>Using multiple connections can help speed up your download.</p></body></html>" ) self.connections_label.setText("Number of connections : ") self.connections_spinBox.setToolTip( "<html><head/><body><p>Using multiple connections can help speed up your download.</p></body></html>" ) self.rpc_port_label.setText("RPC port number : ") self.rpc_port_spinbox.setToolTip( "<html><head/><body><p> Specify a port number for JSON-RPC/XML-RPC server to listen to. Possible Values: 1024 - 65535 Default: 6801 </p></body></html>" ) self.setting_tabWidget.setTabText( self.setting_tabWidget.indexOf(self.download_options_tab), "Download Options") self.download_folder_label.setText("Download Folder : ") self.download_folder_pushButton.setText("Change") self.temp_download_label.setText("Temporary Download Folder : ") self.temp_download_pushButton.setText("Change") self.setting_tabWidget.setTabText( self.setting_tabWidget.indexOf(self.save_as_tab), "Save as") self.enable_notifications_checkBox.setText( "Enable notification sounds") self.volume_label.setText("Volume : ") self.setting_tabWidget.setTabText( self.setting_tabWidget.indexOf(self.notifications_tab), "Notifications") self.style_label.setText("Style : ") self.color_label.setText("Color scheme : ") self.icon_label.setText("Icons : ") self.notification_label.setText("Notification type : ") self.font_label.setText("Font : ") self.font_size_label.setText("Size : ") self.enable_system_tray_checkBox.setText("Enable system tray icon.") self.after_download_checkBox.setText( "Show download complete dialog,when download has finished.") self.show_menubar_checkbox.setText("Show menubar.") self.show_sidepanel_checkbox.setText("Show side panel.") self.show_progress_window_checkbox.setText( "Show download's progress window") self.startup_checkbox.setText("Run Persepolis at startup") self.setting_tabWidget.setTabText( self.setting_tabWidget.indexOf(self.style_tab), "Preferences") self.defaults_pushButton.setText("Defaults") self.cancel_pushButton.setText("Cancel") self.ok_pushButton.setText("OK")
class LogicView(QWidget): def __init__(self, entityLogic): super().__init__() self._entityLogic = entityLogic self._frame = QFrame() self._frame.setFrameStyle(QFrame.WinPanel) self._frame.setFrameShadow(QFrame.Raised) self._frame.setLineWidth(3) self._frameLayout = QVBoxLayout() self._frameLayout.setContentsMargins(0, 0, 0, 0) self._frameLayout.setSpacing(0) self._logicTopBar = LogicViewTopBar() self._frameLayout.addWidget(self._logicTopBar) self._tree = QTreeWidget() self._tree.header().setSectionResizeMode(0, QHeaderView.ResizeToContents) self._tree.setColumnCount(2) self._tree.setHeaderHidden(True) self._tree.setSelectionMode(QTreeWidget.NoSelection) self._tree.verticalScrollBar().setEnabled(False) self._tree.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self._tree.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self._tree.itemCollapsed.connect( self._signal_tree_itemCollapseExpanded) self._tree.itemExpanded.connect(self._signal_tree_itemCollapseExpanded) self._tree.setIndentation(12) self._frameLayout.addWidget(self._tree) self._frame.setLayout(self._frameLayout) self._rootLayout = QVBoxLayout() self._rootLayout.setContentsMargins(0, 0, 0, 0) self._rootLayout.setSpacing(0) self._rootLayout.addWidget(self._frame) self.setLayout(self._rootLayout) self._setupLogic(self._entityLogic) def closeEvent(self, event): super().closeEvent(event) def _setCanCopy(self, copyFlag): self._logicTopBar._setCanCopy(copyFlag) def _updateTreeSize(self): minTreeHeight = GetMinimunWidgetTreeHeight(self._tree) self._tree.setMaximumHeight(minTreeHeight) self._tree.setMinimumHeight(minTreeHeight) minHeight = minTreeHeight + self._logicTopBar.minimumSizeHint().height( ) + 4 self.setMinimumHeight(minHeight) self.setMaximumHeight(minHeight) self.setMinimumWidth(self._tree.sizeHint().width()) def _setupLogic(self, logic): self._entityLogic = logic self._logicTopBar._setupLogic(self._entityLogic) self._tree.clear() self._buildTree(self._tree, self._tree.invisibleRootItem(), self._entityLogic.getValues()) self._updateTreeSize() def _buildArrayTree(self, widgetTree, parentItem, arrayEdit, values): _removeAllItemChildren(parentItem) for value in values: if value.getType() == ValueType.Object: item = QTreeWidgetItem(parentItem) widgetTree.setItemWidget( item, 0, QLabel("<b>{0}</b>".format(value.getName()))) widgetTree.setItemWidget(item, 1, arrayEdit.createObjecValueWrap(value)) self._buildTree(widgetTree, item, value.getValues()) item.setExpanded(True) elif value.getType() == ValueType.Array: raise RuntimeError("Array of arrys not supported") else: item = QTreeWidgetItem(parentItem) item.setText(0, value.getName()) editWidget = self._createEditWidget(value) widgetTree.setItemWidget( item, 1, arrayEdit.createSimpleWrap(editWidget)) parentItem.setExpanded(True) def _buildTree(self, widgetTree, rootItem, values): _removeAllItemChildren(rootItem) for value in values: if value.getType() == ValueType.Object: item = QTreeWidgetItem(rootItem) widgetTree.setItemWidget( item, 0, QLabel("<b>{0}</b>".format(value.getName()))) self._buildTree(widgetTree, item, value.getValues()) item.setExpanded(True) elif value.getType() == ValueType.PolymorphObject: item = QTreeWidgetItem(rootItem) widgetTree.setItemWidget( item, 0, QLabel("<b>{0}</b>".format(value.getName()))) widgetTree.setItemWidget( item, 1, PolymorphTypeSelector(value, item, self)) self._buildTree(widgetTree, item, value.getValues()) item.setExpanded(True) elif value.getType() == ValueType.Array: item = QTreeWidgetItem(rootItem) widgetTree.setItemWidget( item, 0, QLabel("<b>{0}</b>".format(value.getName()))) arrayEdit = EditArrayValue(value, item, self) widgetTree.setItemWidget(item, 1, arrayEdit.createTitle()) self._buildArrayTree(widgetTree, item, arrayEdit, value.getValues()) item.setExpanded(True) else: item = QTreeWidgetItem(rootItem) item.setText(0, value.getName()) item.setToolTip(0, value.getName()) widgetTree.setItemWidget(item, 1, self._createEditWidget(value)) def _signal_tree_itemCollapseExpanded(self, item): self._updateTreeSize() def _createEditWidget(self, value): valType = value.getType() if valType == ValueType.Bool: return EditBoolValue(value) elif valType == ValueType.Int: return EditIntValue(value) elif valType == ValueType.Float: return EditFloatValue(value) elif valType == ValueType.String: return EditStringValue(value) elif valType == ValueType.Vec2i: return EditVec2iValue(value) elif valType == ValueType.Vec2: return EditVec2Value(value) elif valType == ValueType.Vec3: return EditVec3Value(value) elif valType == ValueType.Vec4: return EditVec4Value(value) elif valType == ValueType.Quat: return EditQuatValue(value) elif valType == ValueType.Color: return EditColorValue(value) elif valType == ValueType.Resource: return EditResourceValue(value) elif valType == ValueType.Entity: return EditEntityValue(value) elif valType == ValueType.Array: raise RuntimeError("Invalid value type") elif valType == ValueType.Enum: return EditEnumValue(value) elif valType == ValueType.Object: raise RuntimeError("Object does not have edit widget") else: raise RuntimeError("Unknown Value Type '{0}'".format(valType)) def fetchDataFromNative(self): if not hasattr(self._entityLogic, "readFromNative"): return self._entityLogic.readFromNative() q = [] q.append(self._tree.invisibleRootItem()) while q: currElem = q.pop() editWidget = self._tree.itemWidget(currElem, 1) if editWidget is not None and hasattr(editWidget, "_pull"): editWidget._pull() for i in range(currElem.childCount()): treeItem = currElem.child(i) q.append(treeItem)
class Demo(QMainWindow): def __init__(self): super(Demo, self).__init__() self.jiemian() def boardUI(self): self.board = board1() def b_xianshi(self): # print('wewewef') try: self.num_channel = int(self.board.edit_b1.text()) # print(num_channel) self.num_sample = int(self.board.edit_b2.text()) self.board.monitor.close() self.board.monitor = Stream_Monitor_Widget(self.num_channel, self.num_sample) self.board.board_layout.addWidget(self.board.monitor, 6, 0, 10, 40) except Exception: print('请输入板子参数') try: self.data.org_signal.connect(self.board.monitor.update_plot) self.data.puanduan1 = True except Exception: print('请连接板子') def p_xianshi(self): # print('wewewef') self.num_channel = int(self.board.edit_b1.text()) # print(num_channel) self.num_sample = int(self.board.edit_b2.text()) self.deal.monitor.close() self.deal.monitor = Monitor_Widget(self.num_channel, self.num_sample) self.deal.deal_layout.addWidget(self.deal.monitor, 6, 0, 20, 120) self.data.pre_signal.connect(self.deal.monitor.update_plot) self.data.puanduan2 = True def f_xianshi(self): self.num_channel = int(self.board.edit_b1.text()) # print(num_channel) self.num_sample = int(self.board.edit_b2.text()) self.characteristic.monitor.close() if self.characteristic.chass_combobox.currentIndex() == 1: self.characteristic.monitor = monitor_feature1(self.num_channel, int(int(self.characteristic.edit1_01.text())/2+1)) self.characteristic.chass_layout.addWidget(self.characteristic.monitor, 4, 0, 20, 120) self.data.feature_signal.connect(self.characteristic.monitor.update_plot) elif self.characteristic.chass_combobox.currentIndex() == 2: print(2*(self.num_sample/2+1)) self.characteristic.monitor = monitor_feature2(self.num_channel, int(2*(self.num_sample/2+1))) self.characteristic.chass_layout.addWidget(self.characteristic.monitor, 4, 0, 20, 120) self.data.feature_signal.connect(self.characteristic.monitor.update_plot) elif self.characteristic.chass_combobox.currentIndex() == 3: self.characteristic.monitor = monitor_feature3(self.num_channel, int(self.num_sample/2+1)) self.characteristic.chass_layout.addWidget(self.characteristic.monitor, 4, 0, 20, 120) self.data.feature_signal.connect(self.characteristic.monitor.update_plot) elif self.characteristic.chass_combobox.currentIndex() == 4: self.characteristic.monitor = monitor_feature4(self.characteristic.cca_index) self.characteristic.chass_layout.addWidget(self.characteristic.monitor, 4, 0, 20, 120) self.data.feature_signal.connect(self.characteristic.monitor.update_plot) elif self.characteristic.chass_combobox.currentIndex() == 5: self.characteristic.monitor = monitor_feature5(8) self.characteristic.chass_layout.addWidget(self.characteristic.monitor, 4, 0, 20, 120) self.data.feature_signal.connect(self.characteristic.monitor.update_plot) elif self.characteristic.chass_combobox.currentIndex() == 6: self.characteristic.monitor = monitor_feature6(self.characteristic.fbcca_index) self.characteristic.chass_layout.addWidget(self.characteristic.monitor, 4, 0, 20, 120) self.data.feature_signal.connect(self.characteristic.monitor.update_plot) self.data.puanduan3 = True # def connect(): self.data.command_signal.connect(self.bianhua) def bianhua(self,i): global a if i == "1": a = "1" time.sleep(1) a = "k" elif i == "2": a = "2" time.sleep(1) a = "k" elif i =="3": a = "3" time.sleep(1) a = "k" elif i =="4": a="5" time.sleep(1) a = "k" elif i =="5": a="9" time.sleep(1) a = "k" elif i =="6": a="8" time.sleep(1) a = "k" elif i =="7": a="7" time.sleep(1) a = "k" elif i =="8": a="4" time.sleep(1) a = "k" print(a) def dealUI(self): self.deal = dealui() def characteristicUI(self): self.characteristic = tezheng() def modelUI(self): self.class_model = model() def gameUI(self): self.application = game() def stackSwitch(self, index): self.stackWidget.setCurrentIndex(index) def jiemian(self): # 实例化线程对象 # self.data = MyThread() # 线程自定义信号连接的槽函数 self.test_window1 = QMainWindow() self.setWindowTitle("测试平台") self.setWindowIcon(QIcon('E:/学习/test_platform/Hardware_software_testing/png/脑机接口.jpg')) self.command = QWidget() # 加载页面 self.boardUI() self.dealUI() self.characteristicUI() self.modelUI() self.gameUI() # 设置显示原始数据按钮 self.board.dispay.clicked.connect(self.b_xianshi) # 设置显示预处理数据按钮 self.deal.deal_plot.clicked.connect(self.p_xianshi) # 设置显示特征数据显示 self.characteristic.chass_plot.clicked.connect(self.f_xianshi) # 创建表各界面和QDockWidget界面 # 将列表放到QDockWidget界面中 self.listwidget = QListWidget() self.listwidget.setFixedSize(100, 600) self.listwidget.addItem('脑电放大器') self.listwidget.addItem('脑电预处理') self.listwidget.addItem('脑电特征提取') self.listwidget.addItem('脑电分类模型') self.listwidget.addItem('脑控游戏') font = QFont() font.setFamily("Microsoft YaHei") # 括号里可以设置成自己想要的其它字体 font.setPointSize(11) # 括号里的数字可以设置成自己想要的字体大小 self.listwidget.setFont(font) self.items = QDockWidget() self.items.setWidget(self.listwidget) self.test_window1.addDockWidget(Qt.LeftDockWidgetArea, self.items) # 创建QStackedWidget窗口 self.stackWidget = QStackedWidget() self.stackWidget.addWidget(self.board) self.stackWidget.addWidget(self.deal) self.stackWidget.addWidget(self.characteristic) self.stackWidget.addWidget(self.class_model) self.stackWidget.addWidget(self.application) self.test_window1.setCentralWidget(self.stackWidget) self.listwidget.currentRowChanged.connect(self.stackSwitch) """ 窗口2 """ self.test_window2 = QFrame() self.test_window2.setFrameShape(QFrame.Box) self.test_window2.setFrameShadow(QFrame.Sunken) self.test_window2.setLineWidth(2) self.labe2 = QLabel('结果', self.test_window2) self.button = QPushButton('开始', self.test_window2) self.button.clicked.connect(self.count_func) self.button_2 = QPushButton('停止', self.test_window2) self.button_2.clicked.connect(self.stop_count_func) self.button_3 = QPushButton('传输命令', self.test_window2) self.button_3.clicked.connect(self.contral) self.h_box = QHBoxLayout() self.h_box.addStretch(1) self.h_box.addWidget(self.button) self.h_box.addWidget(self.button_2) self.h_box.addWidget(self.button_3) self.v_box = QVBoxLayout() self.v_box.addWidget(self.labe2) self.v_box.addStretch(1) self.v_box.addLayout(self.h_box) self.test_window2.setLayout(self.v_box) self.splitter = QSplitter() self.splitter.addWidget(self.test_window1) self.splitter.addWidget(self.test_window2) self.splitter.setOrientation(Qt.Vertical) self.setCentralWidget(self.splitter) def contral(self): self.thread_3 = Thread_3() self.thread_3.start() def stop_count_func(self): self.data.is_on = False def count_func(self): # 获取板子参数 board_set = [self.board.boardComboxBox.currentIndex() - 2, self.board.edit_b4.text(), int(self.board.edit_b1.text()), int(self.board.edit_b2.text()), float(self.board.edit_b3.text())] # 获取预处理参数 pre_set1 = [] pre_set2 = [] # 设置预处理1的列表 if self.deal.deal1_combobox.currentIndex() == 1: pre_set1.append(0) pre_set1.append(int(self.deal.edit1_01.text())) pre_set1.append(int(self.deal.edit1_02.text())) pre_set1.append(int(self.deal.edit1_03.text())) pre_set1.append(self.deal.comx1_01.currentIndex() - 1) pre_set1.append(int(self.board.edit_b1.text())) elif self.deal.deal1_combobox.currentIndex() == 2: pre_set1.append(1) pre_set1.append(int(self.deal.edit1_11.text())) pre_set1.append(int(self.deal.edit1_12.text())) pre_set1.append(int(self.deal.edit1_13.text())) pre_set1.append(int(self.deal.edit1_14.text())) pre_set1.append(self.deal.comx1_11.currentIndex() - 1) pre_set1.append(int(self.board.edit_b1.text())) elif self.deal.deal1_combobox.currentIndex() == 3: pre_set1.append(2) pre_set1.append(int(self.deal.edit1_21.text())) pre_set1.append(int(self.deal.edit1_22.text())) pre_set1.append(int(self.deal.edit1_23.text())) pre_set1.append(self.deal.comx1_21.currentIndex() - 1) pre_set1.append(int(self.board.edit_b1.text())) elif self.deal.deal1_combobox.currentIndex() == 4: pre_set1.append(3) pre_set1.append(int(self.board.edit_b2.text())) pre_set1.append(float(self.board.edit_b3.text())) # 设置预处理2列表 if self.deal.deal2_combobox.currentIndex() == 1: pre_set2.append(0) pre_set2.append(self.deal.edit2_02.text()) pre_set2.append(int(self.deal.edit2_01.text())) pre_set2.append(int(self.board.edit_b1.text())) elif self.deal.deal2_combobox.currentIndex() == 2: pre_set2.append(1) pre_set2.append(int(self.deal.edit2_11.text())) pre_set2.append(self.deal.comx2_11.currentIndex() - 1) pre_set2.append(int(self.board.edit_b1.text())) elif self.deal.deal2_combobox.currentIndex() == 3: pre_set2.append(2) pre_set2.append(int(self.board.edit_b1.text())) elif self.deal.deal2_combobox.currentIndex() == 4: pre_set2.append(3) pre_set2.append(int(self.board.edit_b1.text())) elif self.deal.deal2_combobox.currentIndex() == 5: pre_set2.append(4) pre_set = [pre_set1, pre_set2] # 获取特征提取列表 chass_list = [] if self.characteristic.chass_combobox.currentIndex() == 1: chass_list.append(0) chass_list.append(int(self.characteristic.edit1_01.text())) chass_list.append(int(self.characteristic.edit1_02.text())) chass_list.append(int(self.characteristic.edit1_03.text())) chass_list.append(self.characteristic.comx1_01.currentIndex()-1) chass_list.append(int(self.board.edit_b1.text())) elif self.characteristic.chass_combobox.currentIndex() == 2: chass_list.append(1) chass_list.append(self.characteristic.comx1_11.currentIndex()-1) chass_list.append(int(self.board.edit_b1.text())) elif self.characteristic.chass_combobox.currentIndex() == 3: chass_list.append(2) chass_list.append(self.characteristic.comx1_21.currentIndex() - 1) chass_list.append(int(self.board.edit_b1.text())) elif self.characteristic.chass_combobox.currentIndex() == 4: chass = [] chass_list.append(3) for i in range(1, self.characteristic.cca_index + 1, 1): chass.append(float(self.characteristic.lei[i].text())) chass_list.append(chass) chass_list.append(int(self.board.edit_b2.text())) chass_list.append(float(self.board.edit_b3.text())) chass_list.append(self.characteristic.cca_index) elif self.characteristic.chass_combobox.currentIndex() == 5: chass_list.append(4) chass_list.append(8) elif self.characteristic.chass_combobox.currentIndex() == 6: chass = [] chass_list.append(5) for i in range(1, self.characteristic.fbcca_index+1, 1): chass.append(float(self.characteristic.lei2[i].text())) chass_list.append(chass) chass_list.append(int(self.board.edit_b2.text())) chass_list.append(float(self.board.edit_b3.text())) chass_list.append(self.characteristic.fbcca_index) print("列表:",chass_list) # 实例化数据获取 self.data = MyThread(board_set, pre_set, chass_list) self.data.is_on = True self.data.start() # 启动线程
def __init__(self, *args): super().__init__(BrickletLoadCellV2, *args) self.lc = self.device self.cbe_weight = CallbackEmulator(self.lc.get_weight, None, self.cb_weight, self.increase_error_count) self.current_weight = CurveValueWrapper() # int, g self.calibration = None plots = [('Weight', Qt.red, self.current_weight, format_weight)] self.plot_widget = PlotWidget('Weight [g]', plots, y_resolution=1.0) self.button_calibration = QPushButton("Calibration...") self.button_calibration.clicked.connect( self.button_calibration_clicked) self.button_tare = QPushButton("Tare") self.button_tare.clicked.connect(self.button_tare_clicked) self.cbox_info_led_config = QComboBox() self.cbox_info_led_config.addItem("Off") self.cbox_info_led_config.addItem("On") self.cbox_info_led_config.addItem("Heartbeat") self.cbox_info_led_config.currentIndexChanged.connect( self.cbox_info_led_config_changed) self.label_info_led_config = QLabel('Info LED:') self.spin_average = QSpinBox() self.spin_average.setMinimum(0) self.spin_average.setMaximum(40) self.spin_average.setSingleStep(1) self.spin_average.setValue(5) self.spin_average.editingFinished.connect(self.spin_average_finished) self.label_average = QLabel('Moving Average Length:') self.rate_label = QLabel('Rate:') self.rate_combo = QComboBox() self.rate_combo.addItem("10 Hz") self.rate_combo.addItem("80 Hz") self.rate_combo.currentIndexChanged.connect(self.new_config) self.gain_label = QLabel('Gain:') self.gain_combo = QComboBox() self.gain_combo.addItem("128x") self.gain_combo.addItem("64x") self.gain_combo.addItem("32x") self.gain_combo.currentIndexChanged.connect(self.new_config) hlayout = QHBoxLayout() hlayout.addWidget(self.label_average) hlayout.addWidget(self.spin_average) hlayout.addWidget(self.rate_label) hlayout.addWidget(self.rate_combo) hlayout.addWidget(self.gain_label) hlayout.addWidget(self.gain_combo) hlayout.addStretch() hlayout.addWidget(self.button_calibration) hlayout.addWidget(self.button_tare) hlayout.addWidget(self.label_info_led_config) hlayout.addWidget(self.cbox_info_led_config) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
class AddLinkWindow_Ui(QWidget): def __init__(self, persepolis_setting): super().__init__() self.persepolis_setting = persepolis_setting # window -> icons = ':/' + \ str(self.persepolis_setting.value('settings/icons')) + '/' self.setMinimumSize(QtCore.QSize(520, 265)) self.setWindowIcon( QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg'))) window_verticalLayout = QVBoxLayout() window_verticalLayout.setContentsMargins(-1, 10, -1, -1) self.link_frame = QFrame(self) self.link_frame.setFrameShape(QFrame.StyledPanel) self.link_frame.setFrameShadow(QFrame.Raised) horizontalLayout_2 = QHBoxLayout(self.link_frame) link_verticalLayout = QVBoxLayout() # link -> link_horizontalLayout = QHBoxLayout() self.link_label = QLabel(self.link_frame) link_horizontalLayout.addWidget(self.link_label) self.link_lineEdit = QLineEdit(self.link_frame) link_horizontalLayout.addWidget(self.link_lineEdit) link_verticalLayout.addLayout(link_horizontalLayout) horizontalLayout_2.addLayout(link_verticalLayout) window_verticalLayout.addWidget(self.link_frame) # add change_name field -> change_name_horizontalLayout = QHBoxLayout() self.change_name_checkBox = QCheckBox(self.link_frame) change_name_horizontalLayout.addWidget(self.change_name_checkBox) self.change_name_lineEdit = QLineEdit(self.link_frame) change_name_horizontalLayout.addWidget(self.change_name_lineEdit) link_verticalLayout.addLayout(change_name_horizontalLayout) # add_category -> queue_horizontalLayout = QHBoxLayout() self.queue_frame = QFrame(self) self.queue_frame.setFrameShape(QFrame.StyledPanel) self.queue_frame.setFrameShadow(QFrame.Raised) add_queue_horizontalLayout = QHBoxLayout(self.queue_frame) self.add_queue_label = QLabel(self.queue_frame) add_queue_horizontalLayout.addWidget(self.add_queue_label) self.add_queue_comboBox = QComboBox(self.queue_frame) add_queue_horizontalLayout.addWidget(self.add_queue_comboBox) queue_horizontalLayout.addWidget(self.queue_frame) queue_horizontalLayout.addStretch(1) self.size_label = QLabel(self) queue_horizontalLayout.addWidget(self.size_label) window_verticalLayout.addLayout(queue_horizontalLayout) # options_pushButton options_horizontalLayout = QHBoxLayout() self.options_pushButton = QPushButton(self) self.options_pushButton.setFlat(True) options_horizontalLayout.addWidget(self.options_pushButton) options_horizontalLayout.addStretch(1) window_verticalLayout.addLayout(options_horizontalLayout) # proxy -> proxy_verticalLayout = QVBoxLayout() proxy_horizontalLayout = QHBoxLayout() self.proxy_checkBox = QCheckBox(self) self.detect_proxy_pushButton = QPushButton(self) self.detect_proxy_label = QLabel(self) proxy_horizontalLayout.addWidget(self.proxy_checkBox) proxy_horizontalLayout.addWidget(self.detect_proxy_label) proxy_horizontalLayout.addWidget(self.detect_proxy_pushButton) proxy_verticalLayout.addLayout(proxy_horizontalLayout) self.proxy_frame = QFrame(self) self.proxy_frame.setFrameShape(QFrame.StyledPanel) self.proxy_frame.setFrameShadow(QFrame.Raised) gridLayout = QGridLayout(self.proxy_frame) self.ip_lineEdit = QLineEdit(self.proxy_frame) self.ip_lineEdit.setInputMethodHints(QtCore.Qt.ImhNone) gridLayout.addWidget(self.ip_lineEdit, 0, 1, 1, 1) self.proxy_pass_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.proxy_pass_label, 2, 2, 1, 1) self.proxy_pass_lineEdit = QLineEdit(self.proxy_frame) self.proxy_pass_lineEdit.setEchoMode(QLineEdit.Password) gridLayout.addWidget(self.proxy_pass_lineEdit, 2, 3, 1, 1) self.ip_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.ip_label, 0, 0, 1, 1) self.proxy_user_lineEdit = QLineEdit(self.proxy_frame) gridLayout.addWidget(self.proxy_user_lineEdit, 0, 3, 1, 1) self.proxy_user_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.proxy_user_label, 0, 2, 1, 1) self.port_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.port_label, 2, 0, 1, 1) self.port_spinBox = QSpinBox(self.proxy_frame) self.port_spinBox.setMaximum(65535) self.port_spinBox.setSingleStep(1) gridLayout.addWidget(self.port_spinBox, 2, 1, 1, 1) proxy_verticalLayout.addWidget(self.proxy_frame) window_verticalLayout.addLayout(proxy_verticalLayout) # download UserName & Password -> download_horizontalLayout = QHBoxLayout() download_horizontalLayout.setContentsMargins(-1, 10, -1, -1) download_verticalLayout = QVBoxLayout() self.download_checkBox = QCheckBox(self) download_verticalLayout.addWidget(self.download_checkBox) self.download_frame = QFrame(self) self.download_frame.setFrameShape(QFrame.StyledPanel) self.download_frame.setFrameShadow(QFrame.Raised) gridLayout_2 = QGridLayout(self.download_frame) self.download_user_lineEdit = QLineEdit(self.download_frame) gridLayout_2.addWidget(self.download_user_lineEdit, 0, 1, 1, 1) self.download_user_label = QLabel(self.download_frame) gridLayout_2.addWidget(self.download_user_label, 0, 0, 1, 1) self.download_pass_label = QLabel(self.download_frame) gridLayout_2.addWidget(self.download_pass_label, 1, 0, 1, 1) self.download_pass_lineEdit = QLineEdit(self.download_frame) self.download_pass_lineEdit.setEchoMode(QLineEdit.Password) gridLayout_2.addWidget(self.download_pass_lineEdit, 1, 1, 1, 1) download_verticalLayout.addWidget(self.download_frame) download_horizontalLayout.addLayout(download_verticalLayout) # select folder -> self.folder_frame = QFrame(self) self.folder_frame.setFrameShape(QFrame.StyledPanel) self.folder_frame.setFrameShadow(QFrame.Raised) gridLayout_3 = QGridLayout(self.folder_frame) self.download_folder_lineEdit = QLineEdit(self.folder_frame) gridLayout_3.addWidget(self.download_folder_lineEdit, 2, 0, 1, 1) self.folder_pushButton = QPushButton(self.folder_frame) gridLayout_3.addWidget(self.folder_pushButton, 3, 0, 1, 1) self.folder_pushButton.setIcon(QIcon(icons + 'folder')) self.folder_label = QLabel(self.folder_frame) self.folder_label.setAlignment(QtCore.Qt.AlignCenter) gridLayout_3.addWidget(self.folder_label, 1, 0, 1, 1) download_horizontalLayout.addWidget(self.folder_frame) window_verticalLayout.addLayout(download_horizontalLayout) # start time -> time_limit_horizontalLayout = QHBoxLayout() time_limit_horizontalLayout.setContentsMargins(-1, 10, -1, -1) start_verticalLayout = QVBoxLayout() self.start_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.start_checkBox) self.start_frame = QFrame(self) self.start_frame.setFrameShape(QFrame.StyledPanel) self.start_frame.setFrameShadow(QFrame.Raised) horizontalLayout_5 = QHBoxLayout(self.start_frame) self.start_hour_spinBox = QSpinBox(self.start_frame) self.start_hour_spinBox.setMaximum(23) horizontalLayout_5.addWidget(self.start_hour_spinBox) self.start_label = QLabel(self.start_frame) horizontalLayout_5.addWidget(self.start_label) self.start_minute_spinBox = QSpinBox(self.start_frame) self.start_minute_spinBox.setMaximum(59) horizontalLayout_5.addWidget(self.start_minute_spinBox) start_verticalLayout.addWidget(self.start_frame) time_limit_horizontalLayout.addLayout(start_verticalLayout) # end time -> end_verticalLayout = QVBoxLayout() self.end_checkBox = QCheckBox(self) end_verticalLayout.addWidget(self.end_checkBox) self.end_frame = QFrame(self) self.end_frame.setFrameShape(QFrame.StyledPanel) self.end_frame.setFrameShadow(QFrame.Raised) horizontalLayout_6 = QHBoxLayout(self.end_frame) self.end_hour_spinBox = QSpinBox(self.end_frame) self.end_hour_spinBox.setMaximum(23) horizontalLayout_6.addWidget(self.end_hour_spinBox) self.end_label = QLabel(self.end_frame) horizontalLayout_6.addWidget(self.end_label) self.end_minute_spinBox = QSpinBox(self.end_frame) self.end_minute_spinBox.setMaximum(59) horizontalLayout_6.addWidget(self.end_minute_spinBox) end_verticalLayout.addWidget(self.end_frame) time_limit_horizontalLayout.addLayout(end_verticalLayout) # limit Speed -> limit_verticalLayout = QVBoxLayout() self.limit_checkBox = QCheckBox(self) limit_verticalLayout.addWidget(self.limit_checkBox) self.limit_frame = QFrame(self) self.limit_frame.setFrameShape(QFrame.StyledPanel) self.limit_frame.setFrameShadow(QFrame.Raised) horizontalLayout_4 = QHBoxLayout(self.limit_frame) self.limit_spinBox = QDoubleSpinBox(self.limit_frame) self.limit_spinBox.setMinimum(1) self.limit_spinBox.setMaximum(1023) horizontalLayout_4.addWidget(self.limit_spinBox) self.limit_comboBox = QComboBox(self.limit_frame) self.limit_comboBox.addItem("") self.limit_comboBox.addItem("") horizontalLayout_4.addWidget(self.limit_comboBox) limit_verticalLayout.addWidget(self.limit_frame) time_limit_horizontalLayout.addLayout(limit_verticalLayout) window_verticalLayout.addLayout(time_limit_horizontalLayout) # number of connections -> connections_horizontalLayout = QHBoxLayout() connections_horizontalLayout.setContentsMargins(-1, 10, -1, -1) self.connections_frame = QFrame(self) self.connections_frame.setFrameShape(QFrame.StyledPanel) self.connections_frame.setFrameShadow(QFrame.Raised) horizontalLayout_3 = QHBoxLayout(self.connections_frame) self.connections_label = QLabel(self.connections_frame) horizontalLayout_3.addWidget(self.connections_label) self.connections_spinBox = QSpinBox(self.connections_frame) self.connections_spinBox.setMinimum(1) self.connections_spinBox.setMaximum(16) self.connections_spinBox.setProperty("value", 16) horizontalLayout_3.addWidget(self.connections_spinBox) connections_horizontalLayout.addWidget(self.connections_frame) connections_horizontalLayout.addStretch(1) window_verticalLayout.addLayout(connections_horizontalLayout) # ok cancel download_later buttons -> buttons_horizontalLayout = QHBoxLayout() buttons_horizontalLayout.addStretch(1) self.download_later_pushButton = QPushButton(self) self.download_later_pushButton.setIcon(QIcon(icons + 'stop')) self.cancel_pushButton = QPushButton(self) self.cancel_pushButton.setIcon(QIcon(icons + 'remove')) self.ok_pushButton = QPushButton(self) self.ok_pushButton.setIcon(QIcon(icons + 'ok')) buttons_horizontalLayout.addWidget(self.download_later_pushButton) buttons_horizontalLayout.addWidget(self.cancel_pushButton) buttons_horizontalLayout.addWidget(self.ok_pushButton) window_verticalLayout.addLayout(buttons_horizontalLayout) self.setLayout(window_verticalLayout) # labels -> self.setWindowTitle("Enter Your Link") self.link_label.setText("Download Link : ") self.add_queue_label.setText("Add to category : ") self.change_name_checkBox.setText("Change File Name : ") self.options_pushButton.setText("Show more options") self.detect_proxy_pushButton.setText("Detect system proxy setting") self.proxy_checkBox.setText("Proxy") self.proxy_pass_label.setText("Proxy PassWord : "******"IP : ") self.proxy_user_label.setText("Proxy UserName : "******"Port:") self.download_checkBox.setText("Download UserName and PassWord") self.download_user_label.setText("Download UserName : "******"Download PassWord : "******"Change Download Folder") self.folder_label.setText("Download Folder : ") self.start_checkBox.setText("Start Time") self.start_label.setText(":") self.end_checkBox.setText("End Time") self.end_label.setText(":") self.limit_checkBox.setText("Limit Speed") self.limit_comboBox.setItemText(0, "KB/S") self.limit_comboBox.setItemText(1, "MB/S") self.connections_label.setText("Number Of Connections :") self.cancel_pushButton.setText("Cancel") self.ok_pushButton.setText("OK") self.download_later_pushButton.setText("Download later") def changeIcon(self, icons): icons = ':/' + str(icons) + '/' self.folder_pushButton.setIcon(QIcon(icons + 'folder')) self.download_later_pushButton.setIcon(QIcon(icons + 'stop')) self.cancel_pushButton.setIcon(QIcon(icons + 'remove')) self.ok_pushButton.setIcon(QIcon(icons + 'ok'))
def __init__(self, *args): super().__init__(BrickletIndustrialDualAnalogInV2, *args) self.analog_in = self.device self.cbe_voltage0 = CallbackEmulator( self.analog_in.get_voltage, 0, self.cb_voltage, self.increase_error_count, pass_arguments_to_result_callback=True) self.cbe_voltage1 = CallbackEmulator( self.analog_in.get_voltage, 1, self.cb_voltage, self.increase_error_count, pass_arguments_to_result_callback=True) self.calibration = None self.sample_rate_label = QLabel('Sample Rate:') self.sample_rate_combo = QComboBox() self.sample_rate_combo.addItem('976 Hz') self.sample_rate_combo.addItem('488 Hz') self.sample_rate_combo.addItem('244 Hz') self.sample_rate_combo.addItem('122 Hz') self.sample_rate_combo.addItem('61 Hz') self.sample_rate_combo.addItem('4 Hz') self.sample_rate_combo.addItem('2 Hz') self.sample_rate_combo.addItem('1 Hz') self.current_voltage = [CurveValueWrapper(), CurveValueWrapper()] # float, V self.calibration_button = QPushButton('Calibration...') self.sample_rate_combo.currentIndexChanged.connect( self.sample_rate_combo_index_changed) self.calibration_button.clicked.connect( self.calibration_button_clicked) plots = [ ('Channel 0', Qt.red, self.current_voltage[0], format_voltage), ('Channel 1', Qt.blue, self.current_voltage[1], format_voltage) ] self.plot_widget = PlotWidget('Voltage [V]', plots, y_resolution=0.001) # Define lines line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) line1 = QFrame() line1.setObjectName("line1") line1.setFrameShape(QFrame.HLine) line1.setFrameShadow(QFrame.Sunken) line2 = QFrame() line2.setObjectName("line2") line2.setFrameShape(QFrame.HLine) line2.setFrameShadow(QFrame.Sunken) # Define channel LED status config widgets self.led_config_ch0_label = QLabel('Channel 0') self.led_config_ch1_label = QLabel('Channel 1') self.led_config_label = QLabel('LED Config:') self.led_status_config_label = QLabel('LED Status Config:') self.led_status_config_ch0_min_label = QLabel('Min:') self.led_status_config_ch0_max_label = QLabel('Max:') self.led_status_config_ch1_min_label = QLabel('Min:') self.led_status_config_ch1_max_label = QLabel('Max:') self.led_config_ch0_combo = QComboBox() self.led_config_ch0_combo.addItem('Off') self.led_config_ch0_combo.addItem('On') self.led_config_ch0_combo.addItem('Show Heartbeat') self.led_config_ch0_combo.addItem('Show Channel Status') self.led_config_ch0_combo.currentIndexChanged.connect( self.led_config_ch0_combo_changed) self.led_config_ch1_combo = QComboBox() self.led_config_ch1_combo.addItem('Off') self.led_config_ch1_combo.addItem('On') self.led_config_ch1_combo.addItem('Show Heartbeat') self.led_config_ch1_combo.addItem('Show Channel Status') self.led_config_ch1_combo.currentIndexChanged.connect( self.led_config_ch1_combo_changed) self.led_status_config_ch0_combo = QComboBox() self.led_status_config_ch0_combo.addItem('Threshold') self.led_status_config_ch0_combo.addItem('Intensity') self.led_status_config_ch0_combo.currentIndexChanged.connect( self.led_status_config_ch0_combo_changed) self.led_status_config_ch1_combo = QComboBox() self.led_status_config_ch1_combo.addItem('Threshold') self.led_status_config_ch1_combo.addItem('Intensity') self.led_status_config_ch1_combo.currentIndexChanged.connect( self.led_status_config_ch1_combo_changed) self.led_status_config_ch0_min_sbox = QSpinBox() self.led_status_config_ch0_min_sbox.setMinimum(-35000) self.led_status_config_ch0_min_sbox.setMaximum(35000) self.led_status_config_ch0_min_sbox.setValue(0) self.led_status_config_ch0_min_sbox.setSingleStep(1) self.led_status_config_ch0_min_sbox.setSuffix(' mV') self.led_status_config_ch0_min_sbox.valueChanged.connect( self.led_status_config_ch0_min_sbox_changed) self.led_status_config_ch0_max_sbox = QSpinBox() self.led_status_config_ch0_max_sbox.setMinimum(-35000) self.led_status_config_ch0_max_sbox.setMaximum(35000) self.led_status_config_ch0_max_sbox.setValue(0) self.led_status_config_ch0_max_sbox.setSingleStep(1) self.led_status_config_ch0_max_sbox.setSuffix(' mV') self.led_status_config_ch0_max_sbox.valueChanged.connect( self.led_status_config_ch0_max_sbox_changed) self.led_status_config_ch1_min_sbox = QSpinBox() self.led_status_config_ch1_min_sbox.setMinimum(-35000) self.led_status_config_ch1_min_sbox.setMaximum(35000) self.led_status_config_ch1_min_sbox.setValue(0) self.led_status_config_ch1_min_sbox.setSingleStep(1) self.led_status_config_ch1_min_sbox.setSuffix(' mV') self.led_status_config_ch1_min_sbox.valueChanged.connect( self.led_status_config_ch1_min_sbox_changed) self.led_status_config_ch1_max_sbox = QSpinBox() self.led_status_config_ch1_max_sbox.setMinimum(-35000) self.led_status_config_ch1_max_sbox.setMaximum(35000) self.led_status_config_ch1_max_sbox.setValue(0) self.led_status_config_ch1_max_sbox.setSingleStep(1) self.led_status_config_ch1_max_sbox.setSuffix(' mV') self.led_status_config_ch1_max_sbox.valueChanged.connect( self.led_status_config_ch1_max_sbox_changed) # Define size policies h_sp = QSizePolicy() h_sp.setHorizontalPolicy(QSizePolicy.Expanding) # Set size policies self.sample_rate_combo.setSizePolicy(h_sp) self.led_config_ch0_combo.setSizePolicy(h_sp) self.led_config_ch1_combo.setSizePolicy(h_sp) self.led_status_config_ch0_combo.setSizePolicy(h_sp) self.led_status_config_ch1_combo.setSizePolicy(h_sp) self.led_status_config_ch0_min_sbox.setSizePolicy(h_sp) self.led_status_config_ch0_max_sbox.setSizePolicy(h_sp) self.led_status_config_ch1_min_sbox.setSizePolicy(h_sp) self.led_status_config_ch1_max_sbox.setSizePolicy(h_sp) # Define layouts hlayout = QHBoxLayout() vlayout = QVBoxLayout() glayout = QGridLayout() layout = QVBoxLayout(self) hlayout_ch0_min_max = QHBoxLayout() hlayout_ch1_min_max = QHBoxLayout() # Populate layouts vlayout.addWidget(self.calibration_button) hlayout.addWidget(self.sample_rate_label) hlayout.addWidget(self.sample_rate_combo) vlayout.addLayout(hlayout) vlayout.addWidget(line1) hlayout_ch0_min_max.addWidget(self.led_status_config_ch0_min_label) hlayout_ch0_min_max.addWidget(self.led_status_config_ch0_min_sbox) hlayout_ch0_min_max.addWidget(self.led_status_config_ch0_max_label) hlayout_ch0_min_max.addWidget(self.led_status_config_ch0_max_sbox) hlayout_ch1_min_max.addWidget(self.led_status_config_ch1_min_label) hlayout_ch1_min_max.addWidget(self.led_status_config_ch1_min_sbox) hlayout_ch1_min_max.addWidget(self.led_status_config_ch1_max_label) hlayout_ch1_min_max.addWidget(self.led_status_config_ch1_max_sbox) glayout.addWidget(self.led_config_ch0_label, 0, 1, 1, 1) # R, C, RS, CS glayout.addWidget(self.led_config_ch1_label, 0, 2, 1, 1) glayout.addWidget(line2, 1, 0, 1, 3) glayout.addWidget(self.led_config_label, 2, 0, 1, 1) glayout.addWidget(self.led_config_ch0_combo, 2, 1, 1, 1) glayout.addWidget(self.led_config_ch1_combo, 2, 2, 1, 1) glayout.addWidget(self.led_status_config_label, 3, 0, 1, 1) glayout.addWidget(self.led_status_config_ch0_combo, 3, 1, 1, 1) glayout.addWidget(self.led_status_config_ch1_combo, 3, 2, 1, 1) glayout.addLayout(hlayout_ch0_min_max, 4, 1, 1, 1) glayout.addLayout(hlayout_ch1_min_max, 4, 2, 1, 1) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(vlayout) layout.addLayout(glayout) self.ui_group_ch_status_ch0 = [ self.led_status_config_ch0_combo, self.led_status_config_ch0_min_sbox, self.led_status_config_ch0_max_sbox ] self.ui_group_ch_status_ch1 = [ self.led_status_config_ch1_combo, self.led_status_config_ch1_min_sbox, self.led_status_config_ch1_max_sbox ]
def add_tx_stats(self, vbox): hbox_stats = QHBoxLayout() # left column vbox_left = QVBoxLayout() self.tx_desc = TxDetailLabel(word_wrap=True) vbox_left.addWidget(self.tx_desc) self.status_label = TxDetailLabel() vbox_left.addWidget(self.status_label) self.date_label = TxDetailLabel() vbox_left.addWidget(self.date_label) self.amount_label = TxDetailLabel() vbox_left.addWidget(self.amount_label) self.ln_amount_label = TxDetailLabel() vbox_left.addWidget(self.ln_amount_label) fee_hbox = QHBoxLayout() self.fee_label = TxDetailLabel() fee_hbox.addWidget(self.fee_label) self.fee_warning_icon = QLabel() pixmap = QPixmap(icon_path("warning")) pixmap_size = round(2 * char_width_in_lineedit()) pixmap = pixmap.scaled(pixmap_size, pixmap_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.fee_warning_icon.setPixmap(pixmap) self.fee_warning_icon.setVisible(False) fee_hbox.addWidget(self.fee_warning_icon) fee_hbox.addStretch(1) vbox_left.addLayout(fee_hbox) name_fee_hbox = QHBoxLayout() self.name_fee_label = TxDetailLabel() name_fee_hbox.addWidget(self.name_fee_label) name_fee_hbox.addStretch(1) vbox_left.addLayout(name_fee_hbox) vbox_left.addStretch(1) hbox_stats.addLayout(vbox_left, 50) # vertical line separator line_separator = QFrame() line_separator.setFrameShape(QFrame.VLine) line_separator.setFrameShadow(QFrame.Sunken) line_separator.setLineWidth(1) hbox_stats.addWidget(line_separator) # right column vbox_right = QVBoxLayout() self.size_label = TxDetailLabel() vbox_right.addWidget(self.size_label) self.rbf_label = TxDetailLabel() vbox_right.addWidget(self.rbf_label) self.rbf_cb = QCheckBox(_('Replace by fee')) self.rbf_cb.setChecked(bool(self.config.get('use_rbf', True))) vbox_right.addWidget(self.rbf_cb) self.locktime_final_label = TxDetailLabel() vbox_right.addWidget(self.locktime_final_label) locktime_setter_hbox = QHBoxLayout() locktime_setter_hbox.setContentsMargins(0, 0, 0, 0) locktime_setter_hbox.setSpacing(0) locktime_setter_label = TxDetailLabel() locktime_setter_label.setText("LockTime: ") self.locktime_e = LockTimeEdit() locktime_setter_hbox.addWidget(locktime_setter_label) locktime_setter_hbox.addWidget(self.locktime_e) locktime_setter_hbox.addStretch(1) self.locktime_setter_widget = QWidget() self.locktime_setter_widget.setLayout(locktime_setter_hbox) vbox_right.addWidget(self.locktime_setter_widget) self.block_height_label = TxDetailLabel() vbox_right.addWidget(self.block_height_label) vbox_right.addStretch(1) hbox_stats.addLayout(vbox_right, 50) vbox.addLayout(hbox_stats) # below columns self.block_hash_label = TxDetailLabel(word_wrap=True) vbox.addWidget(self.block_hash_label) # set visibility after parenting can be determined by Qt self.rbf_label.setVisible(self.finalized) self.rbf_cb.setVisible(not self.finalized) self.locktime_final_label.setVisible(self.finalized) self.locktime_setter_widget.setVisible(not self.finalized)
class Setting_Ui(QWidget): def __init__(self, persepolis_setting): super().__init__() icon = QIcon() self.persepolis_setting = persepolis_setting # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) self.setWindowIcon( QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg'))) self.setWindowTitle( QCoreApplication.translate("setting_ui_tr", 'Preferences')) # set ui direction ui_direction = self.persepolis_setting.value('ui_direction') if ui_direction == 'rtl': self.setLayoutDirection(Qt.RightToLeft) elif ui_direction in 'ltr': self.setLayoutDirection(Qt.LeftToRight) global icons icons = ':/' + str( self.persepolis_setting.value('settings/icons')) + '/' # main layout window_verticalLayout = QVBoxLayout(self) # setting_tabWidget self.setting_tabWidget = QTabWidget(self) # download_options_tab self.download_options_tab = QWidget() download_options_tab_verticalLayout = QVBoxLayout( self.download_options_tab) download_options_tab_verticalLayout.setContentsMargins(21, 21, 0, 0) # tries tries_horizontalLayout = QHBoxLayout() self.tries_label = QLabel(self.download_options_tab) tries_horizontalLayout.addWidget(self.tries_label) self.tries_spinBox = QSpinBox(self.download_options_tab) self.tries_spinBox.setMinimum(1) tries_horizontalLayout.addWidget(self.tries_spinBox) download_options_tab_verticalLayout.addLayout(tries_horizontalLayout) #wait wait_horizontalLayout = QHBoxLayout() self.wait_label = QLabel(self.download_options_tab) wait_horizontalLayout.addWidget(self.wait_label) self.wait_spinBox = QSpinBox(self.download_options_tab) wait_horizontalLayout.addWidget(self.wait_spinBox) download_options_tab_verticalLayout.addLayout(wait_horizontalLayout) # time_out time_out_horizontalLayout = QHBoxLayout() self.time_out_label = QLabel(self.download_options_tab) time_out_horizontalLayout.addWidget(self.time_out_label) self.time_out_spinBox = QSpinBox(self.download_options_tab) time_out_horizontalLayout.addWidget(self.time_out_spinBox) download_options_tab_verticalLayout.addLayout( time_out_horizontalLayout) # connections connections_horizontalLayout = QHBoxLayout() self.connections_label = QLabel(self.download_options_tab) connections_horizontalLayout.addWidget(self.connections_label) self.connections_spinBox = QSpinBox(self.download_options_tab) self.connections_spinBox.setMinimum(1) self.connections_spinBox.setMaximum(16) connections_horizontalLayout.addWidget(self.connections_spinBox) download_options_tab_verticalLayout.addLayout( connections_horizontalLayout) # rpc_port self.rpc_port_label = QLabel(self.download_options_tab) self.rpc_horizontalLayout = QHBoxLayout() self.rpc_horizontalLayout.addWidget(self.rpc_port_label) self.rpc_port_spinbox = QSpinBox(self.download_options_tab) self.rpc_port_spinbox.setMinimum(1024) self.rpc_port_spinbox.setMaximum(65535) self.rpc_horizontalLayout.addWidget(self.rpc_port_spinbox) download_options_tab_verticalLayout.addLayout( self.rpc_horizontalLayout) # wait_queue wait_queue_horizontalLayout = QHBoxLayout() self.wait_queue_label = QLabel(self.download_options_tab) wait_queue_horizontalLayout.addWidget(self.wait_queue_label) self.wait_queue_time = QDateTimeEdit(self.download_options_tab) self.wait_queue_time.setDisplayFormat('H:mm') wait_queue_horizontalLayout.addWidget(self.wait_queue_time) download_options_tab_verticalLayout.addLayout( wait_queue_horizontalLayout) # change aria2 path aria2_path_verticalLayout = QVBoxLayout() self.aria2_path_checkBox = QCheckBox(self.download_options_tab) aria2_path_verticalLayout.addWidget(self.aria2_path_checkBox) aria2_path_horizontalLayout = QHBoxLayout() self.aria2_path_lineEdit = QLineEdit(self.download_options_tab) aria2_path_horizontalLayout.addWidget(self.aria2_path_lineEdit) self.aria2_path_pushButton = QPushButton(self.download_options_tab) aria2_path_horizontalLayout.addWidget(self.aria2_path_pushButton) aria2_path_verticalLayout.addLayout(aria2_path_horizontalLayout) download_options_tab_verticalLayout.addLayout( aria2_path_verticalLayout) download_options_tab_verticalLayout.addStretch(1) self.setting_tabWidget.addTab(self.download_options_tab, "") # save_as_tab self.save_as_tab = QWidget() save_as_tab_verticalLayout = QVBoxLayout(self.save_as_tab) save_as_tab_verticalLayout.setContentsMargins(20, 30, 0, 0) # download_folder self.download_folder_horizontalLayout = QHBoxLayout() self.download_folder_label = QLabel(self.save_as_tab) self.download_folder_horizontalLayout.addWidget( self.download_folder_label) self.download_folder_lineEdit = QLineEdit(self.save_as_tab) self.download_folder_horizontalLayout.addWidget( self.download_folder_lineEdit) self.download_folder_pushButton = QPushButton(self.save_as_tab) self.download_folder_horizontalLayout.addWidget( self.download_folder_pushButton) save_as_tab_verticalLayout.addLayout( self.download_folder_horizontalLayout) # temp_download_folder self.temp_horizontalLayout = QHBoxLayout() self.temp_download_label = QLabel(self.save_as_tab) self.temp_horizontalLayout.addWidget(self.temp_download_label) self.temp_download_lineEdit = QLineEdit(self.save_as_tab) self.temp_horizontalLayout.addWidget(self.temp_download_lineEdit) self.temp_download_pushButton = QPushButton(self.save_as_tab) self.temp_horizontalLayout.addWidget(self.temp_download_pushButton) save_as_tab_verticalLayout.addLayout(self.temp_horizontalLayout) # create subfolder self.subfolder_checkBox = QCheckBox(self.save_as_tab) save_as_tab_verticalLayout.addWidget(self.subfolder_checkBox) save_as_tab_verticalLayout.addStretch(1) self.setting_tabWidget.addTab(self.save_as_tab, "") # notifications_tab self.notifications_tab = QWidget() notification_tab_verticalLayout = QVBoxLayout(self.notifications_tab) notification_tab_verticalLayout.setContentsMargins(21, 21, 0, 0) self.enable_notifications_checkBox = QCheckBox(self.notifications_tab) notification_tab_verticalLayout.addWidget( self.enable_notifications_checkBox) self.sound_frame = QFrame(self.notifications_tab) self.sound_frame.setFrameShape(QFrame.StyledPanel) self.sound_frame.setFrameShadow(QFrame.Raised) verticalLayout = QVBoxLayout(self.sound_frame) self.volume_label = QLabel(self.sound_frame) verticalLayout.addWidget(self.volume_label) self.volume_dial = QDial(self.sound_frame) self.volume_dial.setProperty("value", 100) verticalLayout.addWidget(self.volume_dial) notification_tab_verticalLayout.addWidget(self.sound_frame) # message_notification message_notification_horizontalLayout = QHBoxLayout() self.notification_label = QLabel(self.notifications_tab) message_notification_horizontalLayout.addWidget( self.notification_label) self.notification_comboBox = QComboBox(self.notifications_tab) message_notification_horizontalLayout.addWidget( self.notification_comboBox) notification_tab_verticalLayout.addLayout( message_notification_horizontalLayout) notification_tab_verticalLayout.addStretch(1) self.setting_tabWidget.addTab(self.notifications_tab, "") # style_tab self.style_tab = QWidget() style_tab_verticalLayout = QVBoxLayout(self.style_tab) style_tab_verticalLayout.setContentsMargins(21, 21, 0, 0) # style style_horizontalLayout = QHBoxLayout() self.style_label = QLabel(self.style_tab) style_horizontalLayout.addWidget(self.style_label) self.style_comboBox = QComboBox(self.style_tab) style_horizontalLayout.addWidget(self.style_comboBox) style_tab_verticalLayout.addLayout(style_horizontalLayout) # language language_horizontalLayout = QHBoxLayout() self.lang_label = QLabel(self.style_tab) language_horizontalLayout.addWidget(self.lang_label) self.lang_comboBox = QComboBox(self.style_tab) language_horizontalLayout.addWidget(self.lang_comboBox) style_tab_verticalLayout.addLayout(language_horizontalLayout) language_horizontalLayout = QHBoxLayout() self.lang_label.setText( QCoreApplication.translate("setting_ui_tr", "Language:")) # color scheme self.color_label = QLabel(self.style_tab) language_horizontalLayout.addWidget(self.color_label) self.color_comboBox = QComboBox(self.style_tab) language_horizontalLayout.addWidget(self.color_comboBox) style_tab_verticalLayout.addLayout(language_horizontalLayout) # icons icons_horizontalLayout = QHBoxLayout() self.icon_label = QLabel(self.style_tab) icons_horizontalLayout.addWidget(self.icon_label) self.icon_comboBox = QComboBox(self.style_tab) icons_horizontalLayout.addWidget(self.icon_comboBox) style_tab_verticalLayout.addLayout(icons_horizontalLayout) self.icons_size_horizontalLayout = QHBoxLayout() self.icons_size_label = QLabel(self.style_tab) self.icons_size_horizontalLayout.addWidget(self.icons_size_label) self.icons_size_comboBox = QComboBox(self.style_tab) self.icons_size_horizontalLayout.addWidget(self.icons_size_comboBox) style_tab_verticalLayout.addLayout(self.icons_size_horizontalLayout) # font font_horizontalLayout = QHBoxLayout() self.font_checkBox = QCheckBox(self.style_tab) font_horizontalLayout.addWidget(self.font_checkBox) self.fontComboBox = QFontComboBox(self.style_tab) font_horizontalLayout.addWidget(self.fontComboBox) self.font_size_label = QLabel(self.style_tab) font_horizontalLayout.addWidget(self.font_size_label) self.font_size_spinBox = QSpinBox(self.style_tab) self.font_size_spinBox.setMinimum(1) font_horizontalLayout.addWidget(self.font_size_spinBox) style_tab_verticalLayout.addLayout(font_horizontalLayout) self.setting_tabWidget.addTab(self.style_tab, "") window_verticalLayout.addWidget(self.setting_tabWidget) # start persepolis in system tray if browser executed self.start_persepolis_if_browser_executed_checkBox = QCheckBox( self.style_tab) style_tab_verticalLayout.addWidget( self.start_persepolis_if_browser_executed_checkBox) # hide window if close button clicked self.hide_window_checkBox = QCheckBox(self.style_tab) style_tab_verticalLayout.addWidget(self.hide_window_checkBox) # Enable system tray icon self.enable_system_tray_checkBox = QCheckBox(self.style_tab) style_tab_verticalLayout.addWidget(self.enable_system_tray_checkBox) # after_download dialog self.after_download_checkBox = QCheckBox() style_tab_verticalLayout.addWidget(self.after_download_checkBox) # show_menubar_checkbox self.show_menubar_checkbox = QCheckBox() style_tab_verticalLayout.addWidget(self.show_menubar_checkbox) # show_sidepanel_checkbox self.show_sidepanel_checkbox = QCheckBox() style_tab_verticalLayout.addWidget(self.show_sidepanel_checkbox) # hide progress window self.show_progress_window_checkbox = QCheckBox() style_tab_verticalLayout.addWidget(self.show_progress_window_checkbox) # add persepolis to startup self.startup_checkbox = QCheckBox() style_tab_verticalLayout.addWidget(self.startup_checkbox) # keep system awake self.keep_awake_checkBox = QCheckBox() style_tab_verticalLayout.addWidget(self.keep_awake_checkBox) style_tab_verticalLayout.addStretch(1) # columns_tab self.columns_tab = QWidget() columns_tab_verticalLayout = QVBoxLayout(self.columns_tab) columns_tab_verticalLayout.setContentsMargins(21, 21, 0, 0) # creating checkBox for columns self.show_column_label = QLabel() self.column0_checkBox = QCheckBox() self.column1_checkBox = QCheckBox() self.column2_checkBox = QCheckBox() self.column3_checkBox = QCheckBox() self.column4_checkBox = QCheckBox() self.column5_checkBox = QCheckBox() self.column6_checkBox = QCheckBox() self.column7_checkBox = QCheckBox() self.column10_checkBox = QCheckBox() self.column11_checkBox = QCheckBox() self.column12_checkBox = QCheckBox() columns_tab_verticalLayout.addWidget(self.show_column_label) columns_tab_verticalLayout.addWidget(self.column0_checkBox) columns_tab_verticalLayout.addWidget(self.column1_checkBox) columns_tab_verticalLayout.addWidget(self.column2_checkBox) columns_tab_verticalLayout.addWidget(self.column3_checkBox) columns_tab_verticalLayout.addWidget(self.column4_checkBox) columns_tab_verticalLayout.addWidget(self.column5_checkBox) columns_tab_verticalLayout.addWidget(self.column6_checkBox) columns_tab_verticalLayout.addWidget(self.column7_checkBox) columns_tab_verticalLayout.addWidget(self.column10_checkBox) columns_tab_verticalLayout.addWidget(self.column11_checkBox) columns_tab_verticalLayout.addWidget(self.column12_checkBox) columns_tab_verticalLayout.addStretch(1) self.setting_tabWidget.addTab(self.columns_tab, '') # video_finder_tab self.video_finder_tab = QWidget() video_finder_layout = QVBoxLayout(self.video_finder_tab) video_finder_layout.setContentsMargins(21, 21, 0, 0) video_finder_tab_verticalLayout = QVBoxLayout() max_links_horizontalLayout = QHBoxLayout() # max_links_label self.max_links_label = QLabel(self.video_finder_tab) max_links_horizontalLayout.addWidget(self.max_links_label) # max_links_spinBox self.max_links_spinBox = QSpinBox(self.video_finder_tab) self.max_links_spinBox.setMinimum(1) self.max_links_spinBox.setMaximum(16) max_links_horizontalLayout.addWidget(self.max_links_spinBox) video_finder_tab_verticalLayout.addLayout(max_links_horizontalLayout) self.video_finder_dl_path_horizontalLayout = QHBoxLayout() self.video_finder_frame = QFrame(self.video_finder_tab) self.video_finder_frame.setLayout(video_finder_tab_verticalLayout) video_finder_tab_verticalLayout.addStretch(1) video_finder_layout.addWidget(self.video_finder_frame) self.setting_tabWidget.addTab(self.video_finder_tab, "") # shortcut tab self.shortcut_tab = QWidget() shortcut_tab_verticalLayout = QVBoxLayout(self.shortcut_tab) shortcut_tab_verticalLayout.setContentsMargins(21, 21, 0, 0) # shortcut_table self.shortcut_table = QTableWidget(self) self.shortcut_table.setColumnCount(2) self.shortcut_table.setSelectionBehavior(QAbstractItemView.SelectRows) self.shortcut_table.setSelectionMode(QAbstractItemView.SingleSelection) self.shortcut_table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.shortcut_table.verticalHeader().hide() shortcut_table_header = [ QCoreApplication.translate("setting_ui_tr", 'Action'), QCoreApplication.translate("setting_ui_tr", 'Shortcut') ] self.shortcut_table.setHorizontalHeaderLabels(shortcut_table_header) shortcut_tab_verticalLayout.addWidget(self.shortcut_table) self.setting_tabWidget.addTab( self.shortcut_tab, QCoreApplication.translate("setting_ui_tr", "Shortcuts")) # Actions actions_list = [ QCoreApplication.translate('setting_ui_tr', 'Quit'), QCoreApplication.translate( 'setting_ui_tr', 'Minimize main window to the tray icon'), QCoreApplication.translate('setting_ui_tr', 'Remove download items'), QCoreApplication.translate('setting_ui_tr', 'Delete download items'), QCoreApplication.translate('setting_ui_tr', 'Move up selected items'), QCoreApplication.translate('setting_ui_tr', 'Move down selected items'), QCoreApplication.translate('setting_ui_tr', 'Add new download link'), QCoreApplication.translate('setting_ui_tr', 'Add new Video link'), QCoreApplication.translate('setting_ui_tr', 'Import links from text file') ] # add actions to the shortcut_table j = 0 for action in actions_list: item = QTableWidgetItem(str(action)) # align center item.setTextAlignment(0x0004 | 0x0080) # insert item in shortcut_table self.shortcut_table.insertRow(j) self.shortcut_table.setItem(j, 0, item) j = j + 1 self.shortcut_table.resizeColumnsToContents() # window buttons buttons_horizontalLayout = QHBoxLayout() buttons_horizontalLayout.addStretch(1) self.defaults_pushButton = QPushButton(self) buttons_horizontalLayout.addWidget(self.defaults_pushButton) self.cancel_pushButton = QPushButton(self) self.cancel_pushButton.setIcon(QIcon(icons + 'remove')) buttons_horizontalLayout.addWidget(self.cancel_pushButton) self.ok_pushButton = QPushButton(self) self.ok_pushButton.setIcon(QIcon(icons + 'ok')) buttons_horizontalLayout.addWidget(self.ok_pushButton) window_verticalLayout.addLayout(buttons_horizontalLayout) # set style_tab for default self.setting_tabWidget.setCurrentIndex(3) # labels and translations self.setWindowTitle( QCoreApplication.translate("setting_ui_tr", "Preferences")) self.tries_label.setToolTip( QCoreApplication.translate( "setting_ui_tr", "<html><head/><body><p>Set number of tries if download failed.</p></body></html>" )) self.tries_label.setText( QCoreApplication.translate("setting_ui_tr", "Number of tries: ")) self.tries_spinBox.setToolTip( QCoreApplication.translate( "setting_ui_tr", "<html><head/><body><p>Set number of tries if download failed.</p></body></html>" )) self.wait_label.setToolTip( QCoreApplication.translate( "setting_ui_tr", "<html><head/><body><p>Set the seconds to wait between retries. Download manager will retry downloads when the HTTP server returns a 503 response.</p></body></html>" )) self.wait_label.setText( QCoreApplication.translate("setting_ui_tr", "Wait between retries (seconds): ")) self.wait_spinBox.setToolTip( QCoreApplication.translate( "setting_ui_tr", "<html><head/><body><p>Set the seconds to wait between retries. Download manager will retry downloads when the HTTP server returns a 503 response.</p></body></html>" )) self.time_out_label.setToolTip( QCoreApplication.translate( "setting_ui_tr", "<html><head/><body><p>Set timeout in seconds. </p></body></html>" )) self.time_out_label.setText( QCoreApplication.translate("setting_ui_tr", "Timeout (seconds): ")) self.time_out_spinBox.setToolTip( QCoreApplication.translate( "setting_ui_tr", "<html><head/><body><p>Set timeout in seconds. </p></body></html>" )) self.connections_label.setToolTip( QCoreApplication.translate( "setting_ui_tr", "<html><head/><body><p>Using multiple connections can help speed up your download.</p></body></html>" )) self.connections_label.setText( QCoreApplication.translate("setting_ui_tr", "Number of connections: ")) self.connections_spinBox.setToolTip( QCoreApplication.translate( "setting_ui_tr", "<html><head/><body><p>Using multiple connections can help speed up your download.</p></body></html>" )) self.rpc_port_label.setText( QCoreApplication.translate("setting_ui_tr", "RPC port number: ")) self.rpc_port_spinbox.setToolTip( QCoreApplication.translate( "setting_ui_tr", "<html><head/><body><p> Specify a port number for JSON-RPC/XML-RPC server to listen to. Possible Values: 1024 - 65535 Default: 6801 </p></body></html>" )) self.wait_queue_label.setText( QCoreApplication.translate( "setting_ui_tr", 'Wait between every downloads in queue:')) self.aria2_path_checkBox.setText( QCoreApplication.translate("setting_ui_tr", 'Change Aria2 default path')) self.aria2_path_pushButton.setText( QCoreApplication.translate("setting_ui_tr", 'Change')) aria2_path_tooltip = QCoreApplication.translate( "setting_ui_tr", "<html><head/><body><p>Attention: Wrong path may have caused problem! Do it carefully or don't change default setting!</p></body></html>" ) self.aria2_path_checkBox.setToolTip(aria2_path_tooltip) self.aria2_path_lineEdit.setToolTip(aria2_path_tooltip) self.aria2_path_pushButton.setToolTip(aria2_path_tooltip) self.setting_tabWidget.setTabText( self.setting_tabWidget.indexOf(self.download_options_tab), QCoreApplication.translate("setting_ui_tr", "Download Options")) self.download_folder_label.setText( QCoreApplication.translate("setting_ui_tr", "Download Folder: ")) self.download_folder_pushButton.setText( QCoreApplication.translate("setting_ui_tr", "Change")) self.temp_download_label.setText( QCoreApplication.translate("setting_ui_tr", "Temporary Download Folder: ")) self.temp_download_pushButton.setText( QCoreApplication.translate("setting_ui_tr", "Change")) self.subfolder_checkBox.setText( QCoreApplication.translate( "setting_ui_tr", "Create subfolders for Music,Videos,... in default download folder" )) self.setting_tabWidget.setTabText( self.setting_tabWidget.indexOf(self.save_as_tab), QCoreApplication.translate("setting_ui_tr", "Save as")) self.enable_notifications_checkBox.setText( QCoreApplication.translate("setting_ui_tr", "Enable notification sounds")) self.volume_label.setText( QCoreApplication.translate("setting_ui_tr", "Volume: ")) self.setting_tabWidget.setTabText( self.setting_tabWidget.indexOf(self.notifications_tab), QCoreApplication.translate("setting_ui_tr", "Notifications")) self.style_label.setText( QCoreApplication.translate("setting_ui_tr", "Style: ")) self.color_label.setText( QCoreApplication.translate("setting_ui_tr", "Color scheme: ")) self.icon_label.setText( QCoreApplication.translate("setting_ui_tr", "Icons: ")) self.icons_size_label.setText( QCoreApplication.translate("setting_ui_tr", "Toolbar's icons size: ")) self.notification_label.setText( QCoreApplication.translate("setting_ui_tr", "Notification type: ")) self.font_checkBox.setText( QCoreApplication.translate("setting_ui_tr", "Font: ")) self.font_size_label.setText( QCoreApplication.translate("setting_ui_tr", "Size: ")) self.hide_window_checkBox.setText( QCoreApplication.translate( "setting_ui_tr", "Hide main window if close button clicked.")) self.hide_window_checkBox.setToolTip( QCoreApplication.translate( "setting_ui_tr", "<html><head/><body><p>This feature may not work in your operating system.</p></body></html>" )) self.start_persepolis_if_browser_executed_checkBox.setText( QCoreApplication.translate( 'setting_ui_tr', 'Start Persepolis in system tray, If browser is executed.')) self.enable_system_tray_checkBox.setText( QCoreApplication.translate("setting_ui_tr", "Enable system tray icon.")) self.after_download_checkBox.setText( QCoreApplication.translate( "setting_ui_tr", "Show download complete dialog when download has finished.")) self.show_menubar_checkbox.setText( QCoreApplication.translate("setting_ui_tr", "Show menubar.")) self.show_sidepanel_checkbox.setText( QCoreApplication.translate("setting_ui_tr", "Show side panel.")) self.show_progress_window_checkbox.setText( QCoreApplication.translate("setting_ui_tr", "Show download's progress window")) self.startup_checkbox.setText( QCoreApplication.translate("setting_ui_tr", "Run Persepolis at startup")) self.keep_awake_checkBox.setText( QCoreApplication.translate("setting_ui_tr", "Keep system awake!")) self.keep_awake_checkBox.setToolTip( QCoreApplication.translate( "setting_ui_tr", "<html><head/><body><p>This option is preventing system from going to sleep.\ This is necessary if your power manager is suspending system automatically. </p></body></html>" )) self.wait_queue_time.setToolTip( QCoreApplication.translate( "setting_ui_tr", "<html><head/><body><p>Format HH:MM</p></body></html>")) self.setting_tabWidget.setTabText( self.setting_tabWidget.indexOf(self.style_tab), QCoreApplication.translate("setting_ui_tr", "Preferences")) # columns_tab self.show_column_label.setText( QCoreApplication.translate("setting_ui_tr", 'Show this columns:')) self.column0_checkBox.setText( QCoreApplication.translate("setting_ui_tr", 'File Name')) self.column1_checkBox.setText( QCoreApplication.translate("setting_ui_tr", 'Status')) self.column2_checkBox.setText( QCoreApplication.translate("setting_ui_tr", 'Size')) self.column3_checkBox.setText( QCoreApplication.translate("setting_ui_tr", 'Downloaded')) self.column4_checkBox.setText( QCoreApplication.translate("setting_ui_tr", 'Percentage')) self.column5_checkBox.setText( QCoreApplication.translate("setting_ui_tr", 'Connections')) self.column6_checkBox.setText( QCoreApplication.translate("setting_ui_tr", 'Transfer rate')) self.column7_checkBox.setText( QCoreApplication.translate("setting_ui_tr", 'Estimated time left')) self.column10_checkBox.setText( QCoreApplication.translate("setting_ui_tr", 'First try date')) self.column11_checkBox.setText( QCoreApplication.translate("setting_ui_tr", 'Last try date')) self.column12_checkBox.setText( QCoreApplication.translate("setting_ui_tr", 'Category')) self.setting_tabWidget.setTabText( self.setting_tabWidget.indexOf(self.columns_tab), QCoreApplication.translate("setting_ui_tr", "Columns customization")) # Video Finder options tab self.setting_tabWidget.setTabText( self.setting_tabWidget.indexOf(self.video_finder_tab), QCoreApplication.translate("setting_ui_tr", "Video Finder Options")) self.max_links_label.setText( QCoreApplication.translate( "setting_ui_tr", 'Maximum number of links to capture:<br/>' '<small>(If browser sends multiple video links at a time)</small>' )) # window buttons self.defaults_pushButton.setText( QCoreApplication.translate("setting_ui_tr", "Defaults")) self.cancel_pushButton.setText( QCoreApplication.translate("setting_ui_tr", "Cancel")) self.ok_pushButton.setText( QCoreApplication.translate("setting_ui_tr", "OK"))
def propertyInserted(self, index, afterIndex): afterItem = self.m_indexToItem[afterIndex] parentItem = self.m_indexToItem.value(index.parent()) newItem = WidgetItem() newItem.parent = parentItem layout = 0 parentWidget = 0 row = -1 if (not afterItem): row = 0 if (parentItem): parentItem.children.insert(0, newItem) else: self.m_children.insert(0, newItem) else: row = self.gridRow(afterItem) + self.gridSpan(afterItem) if (parentItem): parentItem.children.insert(parentItem.children.indexOf(afterItem) + 1, newItem) else: self.m_children.insert(self.m_children.indexOf(afterItem) + 1, newItem) if (not parentItem): layout = self.m_mainLayout parentWidget = self.q_ptr else: if (not parentItem.container): self.m_recreateQueue.removeAll(parentItem) grandParent = parentItem.parent l = 0 oldRow = self.gridRow(parentItem) if (grandParent): l = grandParent.layout else: l = self.m_mainLayout container = QFrame() container.setFrameShape(QFrame.Panel) container.setFrameShadow(QFrame.Raised) parentItem.container = container parentItem.button = self.createButton() self.m_buttonToItem[parentItem.button] = parentItem parentItem.button.toggled.connect(self.slotToggled) parentItem.layout = QGridLayout() container.setLayout(parentItem.layout) if (parentItem.label): l.removeWidget(parentItem.label) parentItem.label.close() parentItem.label = 0 span = 1 if (not parentItem.widget and not parentItem.widgetLabel): span = 2 l.addWidget(parentItem.button, oldRow, 0, 1, span) self.updateItem(parentItem) layout = parentItem.layout parentWidget = parentItem.container newItem.label = QLabel(parentWidget) newItem.label.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)) newItem.widget = self.createEditor(index.property(), parentWidget) if (newItem.widget): newItem.widget.destroyed.connect(self.slotEditorDestroyed) self.m_widgetToItem[newItem.widget] = newItem elif (index.property().hasValue()): newItem.widgetLabel = QLabel(parentWidget) newItem.widgetLabel.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)) self.insertRow(layout, row) span = 1 if (newItem.widget): layout.addWidget(newItem.widget, row, 1) elif (newItem.widgetLabel): layout.addWidget(newItem.widgetLabel, row, 1) else: span = 2 layout.addWidget(newItem.label, row, 0, span, 1) self.m_itemToIndex[newItem] = index self.m_indexToItem[index] = newItem self.updateItem(newItem)
class AddLinkWindow_Ui(QWidget): def __init__(self, persepolis_setting): super().__init__() self.persepolis_setting = persepolis_setting # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # set ui direction ui_direction = self.persepolis_setting.value('ui_direction') if ui_direction == 'rtl': self.setLayoutDirection(Qt.RightToLeft) elif ui_direction in 'ltr': self.setLayoutDirection(Qt.LeftToRight) # get icons name icons = ':/' + \ str(self.persepolis_setting.value('settings/icons')) + '/' self.setMinimumSize(QtCore.QSize(520, 425)) self.setWindowIcon(QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg'))) # main layout window_verticalLayout = QVBoxLayout() # add link tab widget self.add_link_tabWidget = QTabWidget(self) window_verticalLayout.addWidget(self.add_link_tabWidget) # link tab self.link_tab = QWidget() link_tab_verticalLayout = QVBoxLayout(self.link_tab) link_tab_verticalLayout.setContentsMargins(21, 21, 21, 81) self.link_frame = QFrame(self.link_tab) self.link_frame.setFrameShape(QFrame.StyledPanel) self.link_frame.setFrameShadow(QFrame.Raised) horizontalLayout_2 = QHBoxLayout(self.link_frame) self.link_verticalLayout = QVBoxLayout() # link -> self.link_horizontalLayout = QHBoxLayout() self.link_label = QLabel(self.link_frame) self.link_horizontalLayout.addWidget(self.link_label) self.link_lineEdit = QLineEdit(self.link_frame) self.link_horizontalLayout.addWidget(self.link_lineEdit) self.link_verticalLayout.addLayout(self.link_horizontalLayout) horizontalLayout_2.addLayout(self.link_verticalLayout) link_tab_verticalLayout.addWidget(self.link_frame) # add change_name field -> self.change_name_horizontalLayout = QHBoxLayout() self.change_name_checkBox = QCheckBox(self.link_frame) self.change_name_horizontalLayout.addWidget(self.change_name_checkBox) self.change_name_lineEdit = QLineEdit(self.link_frame) self.change_name_horizontalLayout.addWidget(self.change_name_lineEdit) self.link_verticalLayout.addLayout(self.change_name_horizontalLayout) # add_category -> queue_horizontalLayout = QHBoxLayout() self.queue_frame = QFrame(self) self.queue_frame.setFrameShape(QFrame.StyledPanel) self.queue_frame.setFrameShadow(QFrame.Raised) add_queue_horizontalLayout = QHBoxLayout(self.queue_frame) self.add_queue_label = QLabel(self.queue_frame) add_queue_horizontalLayout.addWidget(self.add_queue_label) self.add_queue_comboBox = QComboBox(self.queue_frame) add_queue_horizontalLayout.addWidget(self.add_queue_comboBox) queue_horizontalLayout.addWidget(self.queue_frame) queue_horizontalLayout.addStretch(1) self.size_label = QLabel(self) queue_horizontalLayout.addWidget(self.size_label) link_tab_verticalLayout.addLayout(queue_horizontalLayout) link_tab_verticalLayout.addStretch(1) self.add_link_tabWidget.addTab(self.link_tab, '') # proxy tab self.proxy_tab = QWidget(self) proxy_verticalLayout = QVBoxLayout(self.proxy_tab) proxy_verticalLayout.setContentsMargins(21, 21, 21, 171) proxy_horizontalLayout = QHBoxLayout() self.proxy_checkBox = QCheckBox(self.proxy_tab) self.detect_proxy_pushButton = QPushButton(self.proxy_tab) self.detect_proxy_label = QLabel(self.proxy_tab) proxy_horizontalLayout.addWidget(self.proxy_checkBox) proxy_horizontalLayout.addWidget(self.detect_proxy_label) proxy_horizontalLayout.addWidget(self.detect_proxy_pushButton) proxy_verticalLayout.addLayout(proxy_horizontalLayout) self.proxy_frame = QFrame(self.proxy_tab) self.proxy_frame.setFrameShape(QFrame.StyledPanel) self.proxy_frame.setFrameShadow(QFrame.Raised) gridLayout = QGridLayout(self.proxy_frame) self.ip_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.ip_label, 0, 0, 1, 1) self.ip_lineEdit = QLineEdit(self.proxy_frame) self.ip_lineEdit.setInputMethodHints(QtCore.Qt.ImhNone) gridLayout.addWidget(self.ip_lineEdit, 0, 1, 1, 1) self.port_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.port_label, 0, 2, 1, 1) self.port_spinBox = QSpinBox(self.proxy_frame) self.port_spinBox.setMaximum(65535) self.port_spinBox.setSingleStep(1) gridLayout.addWidget(self.port_spinBox, 0, 3, 1, 1) self.proxy_user_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.proxy_user_label, 2, 0, 1, 1) self.proxy_user_lineEdit = QLineEdit(self.proxy_frame) gridLayout.addWidget(self.proxy_user_lineEdit, 2, 1, 1, 1) self.proxy_pass_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.proxy_pass_label, 2, 2, 1, 1) self.proxy_pass_lineEdit = QLineEdit(self.proxy_frame) self.proxy_pass_lineEdit.setEchoMode(QLineEdit.Password) gridLayout.addWidget(self.proxy_pass_lineEdit, 2, 3, 1, 1) proxy_verticalLayout.addWidget(self.proxy_frame) proxy_verticalLayout.addStretch(1) self.add_link_tabWidget.addTab(self.proxy_tab, '') # more options tab self.more_options_tab = QWidget(self) more_options_tab_verticalLayout = QVBoxLayout(self.more_options_tab) # download UserName & Password -> download_horizontalLayout = QHBoxLayout() download_horizontalLayout.setContentsMargins(-1, 10, -1, -1) download_verticalLayout = QVBoxLayout() self.download_checkBox = QCheckBox(self.more_options_tab) download_verticalLayout.addWidget(self.download_checkBox) self.download_frame = QFrame(self.more_options_tab) self.download_frame.setFrameShape(QFrame.StyledPanel) self.download_frame.setFrameShadow(QFrame.Raised) gridLayout_2 = QGridLayout(self.download_frame) self.download_user_lineEdit = QLineEdit(self.download_frame) gridLayout_2.addWidget(self.download_user_lineEdit, 0, 1, 1, 1) self.download_user_label = QLabel(self.download_frame) gridLayout_2.addWidget(self.download_user_label, 0, 0, 1, 1) self.download_pass_label = QLabel(self.download_frame) gridLayout_2.addWidget(self.download_pass_label, 1, 0, 1, 1) self.download_pass_lineEdit = QLineEdit(self.download_frame) self.download_pass_lineEdit.setEchoMode(QLineEdit.Password) gridLayout_2.addWidget(self.download_pass_lineEdit, 1, 1, 1, 1) download_verticalLayout.addWidget(self.download_frame) download_horizontalLayout.addLayout(download_verticalLayout) # select folder -> self.folder_frame = QFrame(self.more_options_tab) self.folder_frame.setFrameShape(QFrame.StyledPanel) self.folder_frame.setFrameShadow(QFrame.Raised) gridLayout_3 = QGridLayout(self.folder_frame) self.download_folder_lineEdit = QLineEdit(self.folder_frame) gridLayout_3.addWidget(self.download_folder_lineEdit, 2, 0, 1, 1) self.folder_pushButton = QPushButton(self.folder_frame) gridLayout_3.addWidget(self.folder_pushButton, 3, 0, 1, 1) self.folder_pushButton.setIcon(QIcon(icons + 'folder')) self.folder_label = QLabel(self.folder_frame) self.folder_label.setAlignment(QtCore.Qt.AlignCenter) gridLayout_3.addWidget(self.folder_label, 1, 0, 1, 1) download_horizontalLayout.addWidget(self.folder_frame) more_options_tab_verticalLayout.addLayout(download_horizontalLayout) # start time -> time_limit_horizontalLayout = QHBoxLayout() time_limit_horizontalLayout.setContentsMargins(-1, 10, -1, -1) start_verticalLayout = QVBoxLayout() self.start_checkBox = QCheckBox(self.more_options_tab) start_verticalLayout.addWidget(self.start_checkBox) self.start_frame = QFrame(self.more_options_tab) self.start_frame.setFrameShape(QFrame.StyledPanel) self.start_frame.setFrameShadow(QFrame.Raised) horizontalLayout_5 = QHBoxLayout(self.start_frame) self.start_time_qDataTimeEdit = QDateTimeEdit(self.start_frame) self.start_time_qDataTimeEdit.setDisplayFormat('H:mm') horizontalLayout_5.addWidget(self.start_time_qDataTimeEdit) start_verticalLayout.addWidget(self.start_frame) time_limit_horizontalLayout.addLayout(start_verticalLayout) # end time -> end_verticalLayout = QVBoxLayout() self.end_checkBox = QCheckBox(self.more_options_tab) end_verticalLayout.addWidget(self.end_checkBox) self.end_frame = QFrame(self.more_options_tab) self.end_frame.setFrameShape(QFrame.StyledPanel) self.end_frame.setFrameShadow(QFrame.Raised) horizontalLayout_6 = QHBoxLayout(self.end_frame) self.end_time_qDateTimeEdit = QDateTimeEdit(self.end_frame) self.end_time_qDateTimeEdit.setDisplayFormat('H:mm') horizontalLayout_6.addWidget(self.end_time_qDateTimeEdit) end_verticalLayout.addWidget(self.end_frame) time_limit_horizontalLayout.addLayout(end_verticalLayout) # limit Speed -> limit_verticalLayout = QVBoxLayout() self.limit_checkBox = QCheckBox(self.more_options_tab) limit_verticalLayout.addWidget(self.limit_checkBox) self.limit_frame = QFrame(self.more_options_tab) self.limit_frame.setFrameShape(QFrame.StyledPanel) self.limit_frame.setFrameShadow(QFrame.Raised) horizontalLayout_4 = QHBoxLayout(self.limit_frame) self.limit_spinBox = QDoubleSpinBox(self.limit_frame) self.limit_spinBox.setMinimum(1) self.limit_spinBox.setMaximum(1023) horizontalLayout_4.addWidget(self.limit_spinBox) self.limit_comboBox = QComboBox(self.limit_frame) self.limit_comboBox.addItem("") self.limit_comboBox.addItem("") horizontalLayout_4.addWidget(self.limit_comboBox) limit_verticalLayout.addWidget(self.limit_frame) time_limit_horizontalLayout.addLayout(limit_verticalLayout) more_options_tab_verticalLayout.addLayout(time_limit_horizontalLayout) # number of connections -> connections_horizontalLayout = QHBoxLayout() connections_horizontalLayout.setContentsMargins(-1, 10, -1, -1) self.connections_frame = QFrame(self.more_options_tab) self.connections_frame.setFrameShape(QFrame.StyledPanel) self.connections_frame.setFrameShadow(QFrame.Raised) horizontalLayout_3 = QHBoxLayout(self.connections_frame) self.connections_label = QLabel(self.connections_frame) horizontalLayout_3.addWidget(self.connections_label) self.connections_spinBox = QSpinBox(self.connections_frame) self.connections_spinBox.setMinimum(1) self.connections_spinBox.setMaximum(16) self.connections_spinBox.setProperty("value", 16) horizontalLayout_3.addWidget(self.connections_spinBox) connections_horizontalLayout.addWidget(self.connections_frame) connections_horizontalLayout.addStretch(1) more_options_tab_verticalLayout.addLayout(connections_horizontalLayout) more_options_tab_verticalLayout.addStretch(1) self.add_link_tabWidget.addTab(self.more_options_tab, '') # advance options self.advance_options_tab = QWidget(self) advance_options_tab_verticalLayout = QVBoxLayout(self.advance_options_tab) # referer referer_horizontalLayout = QHBoxLayout() self.referer_label = QLabel(self.advance_options_tab) referer_horizontalLayout.addWidget(self.referer_label) self.referer_lineEdit = QLineEdit(self.advance_options_tab) referer_horizontalLayout.addWidget(self.referer_lineEdit) advance_options_tab_verticalLayout.addLayout(referer_horizontalLayout) # header header_horizontalLayout = QHBoxLayout() self.header_label = QLabel(self.advance_options_tab) header_horizontalLayout.addWidget(self.header_label) self.header_lineEdit = QLineEdit(self.advance_options_tab) header_horizontalLayout.addWidget(self.header_lineEdit) advance_options_tab_verticalLayout.addLayout(header_horizontalLayout) # user_agent user_agent_horizontalLayout = QHBoxLayout() self.user_agent_label = QLabel(self.advance_options_tab) user_agent_horizontalLayout.addWidget(self.user_agent_label) self.user_agent_lineEdit = QLineEdit(self.advance_options_tab) user_agent_horizontalLayout.addWidget(self.user_agent_lineEdit) advance_options_tab_verticalLayout.addLayout(user_agent_horizontalLayout) # load_cookies load_cookies_horizontalLayout = QHBoxLayout() self.load_cookies_label = QLabel(self.advance_options_tab) load_cookies_horizontalLayout.addWidget(self.load_cookies_label) self.load_cookies_lineEdit = QLineEdit(self.advance_options_tab) load_cookies_horizontalLayout.addWidget(self.load_cookies_lineEdit) advance_options_tab_verticalLayout.addLayout(load_cookies_horizontalLayout) advance_options_tab_verticalLayout.addStretch(1) self.add_link_tabWidget.addTab(self.advance_options_tab, '') # ok cancel download_later buttons -> buttons_horizontalLayout = QHBoxLayout() buttons_horizontalLayout.addStretch(1) self.download_later_pushButton = QPushButton(self) self.download_later_pushButton.setIcon(QIcon(icons + 'stop')) self.cancel_pushButton = QPushButton(self) self.cancel_pushButton.setIcon(QIcon(icons + 'remove')) self.ok_pushButton = QPushButton(self) self.ok_pushButton.setIcon(QIcon(icons + 'ok')) buttons_horizontalLayout.addWidget(self.download_later_pushButton) buttons_horizontalLayout.addWidget(self.cancel_pushButton) buttons_horizontalLayout.addWidget(self.ok_pushButton) window_verticalLayout.addLayout(buttons_horizontalLayout) self.setLayout(window_verticalLayout) # labels -> self.setWindowTitle(QCoreApplication.translate("addlink_ui_tr", "Enter Your Link")) self.link_label.setText(QCoreApplication.translate("addlink_ui_tr", "Download Link: ")) self.add_queue_label.setText(QCoreApplication.translate("addlink_ui_tr", "Add to category: ")) self.change_name_checkBox.setText(QCoreApplication.translate("addlink_ui_tr", "Change File Name: ")) self.detect_proxy_pushButton.setText(QCoreApplication.translate("addlink_ui_tr", "Detect system proxy setting")) self.proxy_checkBox.setText(QCoreApplication.translate("addlink_ui_tr", "Proxy")) self.proxy_pass_label.setText(QCoreApplication.translate("addlink_ui_tr", "Proxy PassWord: "******"addlink_ui_tr", "IP: ")) self.proxy_user_label.setText(QCoreApplication.translate("addlink_ui_tr", "Proxy UserName: "******"addlink_ui_tr", "Port:")) self.download_checkBox.setText(QCoreApplication.translate("addlink_ui_tr", "Download UserName and PassWord")) self.download_user_label.setText(QCoreApplication.translate("addlink_ui_tr", "Download UserName: "******"addlink_ui_tr", "Download PassWord: "******"addlink_ui_tr", "Change Download Folder")) self.folder_label.setText(QCoreApplication.translate("addlink_ui_tr", "Download Folder: ")) self.start_checkBox.setText(QCoreApplication.translate("addlink_ui_tr", "Start Time")) self.end_checkBox.setText(QCoreApplication.translate("addlink_ui_tr", "End Time")) self.limit_checkBox.setText(QCoreApplication.translate("addlink_ui_tr", "Limit Speed")) self.limit_comboBox.setItemText(0, "KiB/s") self.limit_comboBox.setItemText(1, "MiB/s") self.connections_label.setText(QCoreApplication.translate("addlink_ui_tr", "Number Of Connections:")) self.cancel_pushButton.setText(QCoreApplication.translate("addlink_ui_tr", "Cancel")) self.ok_pushButton.setText(QCoreApplication.translate("addlink_ui_tr", "OK")) self.download_later_pushButton.setText(QCoreApplication.translate("addlink_ui_tr", "Download later")) self.add_link_tabWidget.setTabText(self.add_link_tabWidget.indexOf( self.link_tab), QCoreApplication.translate("addlink_ui_tr", "Link")) self.add_link_tabWidget.setTabText(self.add_link_tabWidget.indexOf( self.proxy_tab), QCoreApplication.translate("addlink_ui_tr", "Proxy")) self.add_link_tabWidget.setTabText(self.add_link_tabWidget.indexOf( self.more_options_tab), QCoreApplication.translate("addlink_ui_tr", "More Options")) self.add_link_tabWidget.setTabText(self.add_link_tabWidget.indexOf( self.advance_options_tab), QCoreApplication.translate("addlink_ui_tr", "Advanced Options")) self.referer_label.setText(QCoreApplication.translate("addlink_ui_tr", 'Referrer: ')) self.header_label.setText(QCoreApplication.translate("addlink_ui_tr", 'Header: ')) self.load_cookies_label.setText(QCoreApplication.translate("addlink_ui_tr", 'Load cookies: ')) self.user_agent_label.setText(QCoreApplication.translate("addlink_ui_tr", 'User agent: '))