Пример #1
1
 def _initialize(self):
     ## self.paramTPerm = self.field("paramTPerm")
     self.tabs.clear()
     self.total_answers = 0
     self.radioGroups = {}
     filas = self.paramNPerm
     for x in range(filas):
         mygroupbox = QScrollArea()
         mygroupbox.setWidget(QWidget())
         mygroupbox.setWidgetResizable(True)
         myform = QHBoxLayout(mygroupbox.widget())
         cols = self.paramNCols.split(',')
         ansID = 0
         radioGroupList = {}
         for col in cols:
             mygroupboxCol = QGroupBox()
             myformCol = QFormLayout()
             mygroupboxCol.setLayout(myformCol)
             for y in range(int(col)):
                 ansID += 1
                 radioGroupList[ansID] = QButtonGroup()
                 layoutRow = QHBoxLayout()
                 for j in range(self.paramNAlts):
                     myradio = QRadioButton(chr(97+j).upper())
                     layoutRow.addWidget(myradio)
                     radioGroupList[ansID].addButton(myradio)
                 self.total_answers  += 1
                 myformCol.addRow(str(ansID), layoutRow)
             myform.addWidget(mygroupboxCol)
         self.radioGroups[chr(97+x).upper()] = radioGroupList
         self.tabs.addTab(mygroupbox, _('Model ') + chr(97+x).upper())
Пример #2
0
	def __init__(self, message, title):
		super(ErrorMessage, self).__init__()
		self.message = message

		# self.setWindowTitle(title)
		self.setStyleSheet(style.style_loader.stylesheet)

		self.label = QLabel(str(self.message), self)

		self.label_widget = QWidget(self)
		label_layout = QBoxLayout(QBoxLayout.LeftToRight)
		label_layout.addWidget(self.label)
		self.label_widget.setLayout(label_layout)

		self.submit_btn = QPushButton('OK', self)
		self.submit_btn.clicked.connect(self.submit)

		self.submit_btn_widget = QWidget(self)
		submit_btn_layout = QBoxLayout(QBoxLayout.LeftToRight)
		submit_btn_layout.addWidget(self.submit_btn)
		self.submit_btn_widget.setLayout(submit_btn_layout)

		layout = QFormLayout()
		layout.addRow(self.label_widget)
		layout.addRow(self.submit_btn_widget)
		self.setLayout(layout)

		self.show()
		self.setFixedHeight(self.height())
		self.setFixedWidth(self.width())
		self.close()
 def __init__(self):
     super().__init__()
     self.setWindowTitle('Phone Book.')
     self.name = QLineEdit()
     self.number = QLineEdit()
     entry = QFormLayout()
     entry.addRow(QLabel('Name'), self.name)
     entry.addRow(QLabel('Number'), self.number)
     buttons = QHBoxLayout()
     button = QPushButton('&Add')
     button.clicked.connect(self._addEntry)
     buttons.addWidget(button)
     button = QPushButton('&Update')
     button.clicked.connect(self._updateEntry)
     buttons.addWidget(button)
     button = QPushButton('&Delete')
     button.clicked.connect(self._deleteEntry)
     buttons.addWidget(button)
     dataDisplay = QTableView()
     dataDisplay.setModel(PhoneDataModel())
     layout = QVBoxLayout()
     layout.addLayout(entry)
     layout.addLayout(buttons)
     layout.addWidget(dataDisplay)
     self.setLayout(layout)
     self.show()
Пример #4
0
    def __init__(self, parent=None):
        super(LocationFilterPage, self).__init__(parent)

        self.xSpinBox = QDoubleSpinBox()
        self.xSpinBox.setMinimum(float('-inf'))
        self.xSpinBox.setMaximum(float('inf'))
        self.xSpinBox.setDecimals(6)

        self.ySpinBox = QDoubleSpinBox()
        self.ySpinBox.setMinimum(float('-inf'))
        self.ySpinBox.setMaximum(float('inf'))
        self.ySpinBox.setDecimals(6)

        self.tolSpinBox = QDoubleSpinBox()
        self.tolSpinBox.setMinimum(0)
        self.tolSpinBox.setMaximum(float('inf'))
        self.tolSpinBox.setDecimals(6)

        groupLayout = QFormLayout()
        groupLayout.addRow("X:", self.xSpinBox)
        groupLayout.addRow("Y:", self.ySpinBox)
        groupLayout.addRow("Tolerance:", self.tolSpinBox)

        self.group = QGroupBox("Lokace")
        self.group.setCheckable(True)
        self.group.setChecked(False)
        self.group.setLayout(groupLayout)

        layout = QVBoxLayout()
        layout.addWidget(self.group)
        layout.addStretch(1)

        self.setLayout(layout)
Пример #5
0
    def __init__(self, parent=None):
        super(BasicFilterPage, self).__init__(parent)

        self.blockCombo = QComboBox()
        self.deviceCombo = QComboBox()
        self.unitCombo = QComboBox()

        self.combos = {'block': self.blockCombo, \
                       'device': self.deviceCombo, \
                       'unit': self.unitCombo}

        groupLayout = QFormLayout()
        groupLayout.addRow("Skupina měření:", self.blockCombo)
        groupLayout.addRow("Přístroj:", self.deviceCombo)
        groupLayout.addRow("Veličina:", self.unitCombo)

        filterGroup = QGroupBox("Základní filtry")
        filterGroup.setLayout(groupLayout)

        self.deviatedValuesCheckbox = QCheckBox()
        valuesLayout = QFormLayout()
        valuesLayout.addRow("Mimo odchylku:", self.deviatedValuesCheckbox)

        valuesGroup = QGroupBox("Hodnoty")
        valuesGroup.setLayout(valuesLayout)

        layout = QVBoxLayout()
        layout.addWidget(filterGroup)
        layout.addSpacing(12)
        layout.addWidget(valuesGroup)
        layout.addStretch(1)

        self.setLayout(layout)
Пример #6
0
    def __init__(self, parent=None, **kwargs):
        super().__init__(parent, **kwargs)

        self._limits = []

        self.setLayout(QVBoxLayout())
        self.form_set = QFormLayout()
        self.form_lim = QFormLayout()
        self.layout().addLayout(self.form_set)
        self.layout().addLayout(self.form_lim)

        self.methodcb = QComboBox()
        self.methodcb.addItems(self.Integrators)

        self.form_set.addRow("Integration method:", self.methodcb)
        self.methodcb.currentIndexChanged.connect(self.changed)
        self.methodcb.activated.connect(self.edited)

        self.focusIn = self.activateOptions

        self.add_limit()

        button = QPushButton("Add Region")
        self.layout().addWidget(button)
        button.clicked.connect(self.add_limit)

        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)

        self.user_changed = False
Пример #7
0
    def createChartView(
            self, _x2idx: dict, _idx2x: list
    ) -> QHBoxLayout:
        chart = QChart()

        # assign y range
        self.calcRangeY()
        self.setAxisY(self.begin_y, self.end_y)

        value_layout = QFormLayout()
        # add each series
        for v in self.series_table.values():
            v.addSeries(_x2idx, _idx2x, chart, self.axis_x, self.axis_y)
            if v.show_value:
                value_layout.addWidget(v.show_group)

        # create chartview and layout for view and value
        chartview = ChartView(chart, self.wizard)
        chartview.setRenderHint(QPainter.Antialiasing)

        global_layout = QHBoxLayout()
        global_layout.addWidget(chartview, self.chart_stretch)
        global_layout.addLayout(value_layout)

        return global_layout
Пример #8
0
    def __populate_groupbox(self):
        """

        """
        layout = QVBoxLayout()
        self.groupbox.setLayout(layout)

        first_line = QHBoxLayout()

        self.visibility_label = QLabel("Show ROI:")
        first_line.addWidget(self.visibility_label)
        self.visibility_checkbox = QCheckBox(self)
        self.visibility_checkbox.setCheckable(True)
        self.visibility_checkbox.toggled.connect(self.__checkbox_cb)
        first_line.addWidget(self.visibility_checkbox)
        self.select_button = QPushButton("+", self)
        self.select_button.setToolTip("Select ROI with the mouse")
        self.select_button.clicked.connect(self.activate_selection)
        first_line.addWidget(self.select_button)

        layout.addLayout(first_line)

        form_layout = QFormLayout()
        layout.addLayout(form_layout)

        for prop in self.group.properties:
            form_layout.addRow(prop.prop.name, prop)
Пример #9
0
    def setup_path_widgets(self):
        path_layout = QFormLayout()
        path_layout.addRow("Root:", self.widgets['path/project_root'])
        path_layout.addRow("Maps from:", self.widgets['path/path_mapping'])

        self.path_group = QGroupBox("Path")
        self.path_group.setLayout(path_layout)
Пример #10
0
 def createShow(self):
     self.show_group = QGroupBox()
     self.show_group.setTitle(self.name)
     self.show_edit = QLineEdit()
     self.show_edit.setDisabled(True)
     layout = QFormLayout()
     layout.addWidget(self.show_edit)
     self.show_group.setLayout(layout)
Пример #11
0
class QtFormView(QWidget):
    def __init__(self, parent=None):
        super(QtFormView, self).__init__(parent)
        self.form_layout = QFormLayout()    
        self.setLayout(self.form_layout)

    def add_row(self, label, widget):
        self.form_layout.addRow(label, widget)
Пример #12
0
    def __init__(self, title, config):
        QDialog.__init__(self)
        if config is not None:
            self.type = config.type
        else:
            self.type = JDEROBOTCOMM

        self.setWindowTitle(title)
        commSelectionBox = QGroupBox('Select Communication Interface')
        commSelectionBox.setObjectName('commInterface')
        # add new config input fields
        fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        self.commTypeCombo = QComboBox()
        self.commTypeCombo.setFont(fixedWidthFont)
        self.commTypeCombo.setMaximumWidth(220)
        boxLayout = QVBoxLayout()
        boxLayout.addWidget(self.commTypeCombo)
        commSelectionBox.setLayout(boxLayout)
        vLayout = QFormLayout()
        vLayout.addWidget(commSelectionBox)

        self.configsLayout = QVBoxLayout()
        self.configsBox = QGroupBox('')
        self.configsBox.setLayout(self.configsLayout)
        vLayout.addWidget(self.configsBox)

        self.setLayout(vLayout)
        self.resize(700, 500)
        #self.setStyleSheet('QGroupBox#commInterface { border: 1px solid black; border-radius: 4px; padding:15px;} QGroupBox::title#commInterface {background-color:transparent; padding-left:25px; padding-top:5px;} ')

        self.rosConfigsUI = RosConfigDialog('ROS Communication')
        self.rosConfigsUI.configChanged.connect(self.configChangedHandler)
        self.configsLayout.addWidget(self.rosConfigsUI)
        self.rosConfigsUI.setVisible(False)
        self.jderobotCommConfigsUI = JdeRobotCommConfigDialog('JdeRobot Communication')
        self.jderobotCommConfigsUI.configChanged.connect(self.configChangedHandler)
        self.configsLayout.addWidget(self.jderobotCommConfigsUI)
        self.jderobotCommConfigsUI.setVisible(True)

        self.rosConfig = None
        self.jdeRobotCommConfig = None

        self.commTypeCombo.addItem('JdeRobot Communication', 'jderobotcomm')
        self.commTypeCombo.addItem('ROS Node', 'ros')
        self.commTypeCombo.currentIndexChanged.connect(self.commTypeComboChanged)

        if config is not None:
            if config.type == ROS:
                self.rosConfig = config
                self.commTypeCombo.setCurrentIndex(1)
                self.loadRosConfigs()
            elif config.type == JDEROBOTCOMM:
                self.jdeRobotCommConfig = config
                self.commTypeCombo.setCurrentIndex(0)
                self.loadJdeRobotCommConfigs()
        else:
            self.loadJdeRobotCommConfigs()
Пример #13
0
    def __init__(self, *args, **kwargs):
        # Add the layout.
        layout = QFormLayout()
        super().__init__("Create a new task", layout, *args, **kwargs)

        # Add the input fields.
        self.input_title = QLineEdit()
        layout.addRow("Title:", self.input_title)
        self.input_description = QPlainTextEdit()
        layout.addRow("Description:", self.input_description)
Пример #14
0
 def __init__(self):
     super().__init__()
     self.setTitle(_('Configuration of exam params'))
     self.setSubTitle(_('Enter the configuration parameters of the exam'))
     layout = QFormLayout(self)
     self.setLayout(layout)
     self.paramNEIDs = widgets.InputInteger(
         initial_value=8, min_value=0, max_value=16)
     self.registerField("paramNEIDs", self.paramNEIDs)
     self.paramNAlts = widgets.InputInteger(initial_value=3)
     self.registerField("paramNAlts", self.paramNAlts)
     self.paramNCols = widgets.InputCustomPattern(fixed_size=250,
                                       regex=r'[1-9][0-9]?(\,[1-9][0-9]?)+',
                                       placeholder=_('num,num,...'))
     self.registerField("paramNCols", self.paramNCols)
     self.paramNPerm = widgets.InputInteger(min_value=1, initial_value=2)
     self.registerField("paramNPerm", self.paramNPerm)
     ## self.paramTPerm = widgets.CustomComboBox(parent=self)
     ## self.paramTPerm.set_items([
     ##     _('No (recommended)'),
     ##     _('Yes (experimental)'),
     ## ])
     ## self.paramTPerm.setCurrentIndex(0)
     ## self.registerField("paramTPerm", self.paramTPerm)
     layout.addRow(_('Number of digits of the student ID '
                     '(0 to not scan IDs)'),
                   self.paramNEIDs)
     layout.addRow(_('Number of choices per question'),
                   self.paramNAlts)
     layout.addRow(_('Number of questions per answer box'),
                   self.paramNCols)
     layout.addRow(_('Number of models of the exam'),
                   self.paramNPerm)
Пример #15
0
    def _setup_keybindings_ui(self):
        """
        Create everything related to the keybindings tab
        """

        layout = QFormLayout()
        self.keybinding_fullscreen_label = QLabel("Toggle Fullscreen:")
        self.keybinding_fullscreen = QKeySequenceEdit()
        layout.addRow(self.keybinding_fullscreen_label,
                      self.keybinding_fullscreen)

        self.keybinding_save_image_label = QLabel("Save image:")
        self.keybinding_save_image = QKeySequenceEdit(QKeySequence(self.settings.keybinding_save_image))
        layout.addRow(self.keybinding_save_image_label,
                      self.keybinding_save_image)

        self.keybinding_trigger_image_label = QLabel("Trigger images via softwaretrigger:")
        self.keybinding_trigger_image = QKeySequenceEdit(QKeySequence(self.settings.keybinding_trigger_image))
        layout.addRow(self.keybinding_trigger_image_label,
                      self.keybinding_trigger_image)

        self.keybinding_open_dialog_label = QLabel("Open device dialog:")
        self.keybinding_open_dialog = QKeySequenceEdit(QKeySequence(self.settings.keybinding_open_dialog))
        layout.addRow(self.keybinding_open_dialog_label,
                      self.keybinding_open_dialog)

        self.keybindings_widget.setLayout(layout)
Пример #16
0
    def __init__(self, editor):
        super(FindReplaceDialog, self).__init__()
        self._editor = editor
        layout = QFormLayout()
        layout.setFieldGrowthPolicy(layout.AllNonFixedFieldsGrow)
        self.button_box = QDialogButtonBox()

        self.find_button = self._add_button(
            "Find", self.button_box.ActionRole, self.do_find)
        self.replace_button = self._add_button(
            "Replace", self.button_box.ActionRole, self.do_replace)
        self.replace_all_button = self._add_button(
            "Replace All", self.button_box.ActionRole, self.do_replace_all)

        self.button_box.addButton(self.button_box.Close)
        self.button_box.rejected.connect(self.reject)
        self.find_input = QLineEdit()
        self.find_input.textChanged.connect(self.on_text_changed)
        self.replace_input = QLineEdit()
        layout.addRow('Find', self.find_input)
        layout.addRow('Replace With:', self.replace_input)
        layout.addRow(self.button_box)
        self.setLayout(layout)
        self.resize(QSize(450, 150))
        self.setWindowTitle("Find / Replace")
        # Trigger an update to the button enabled-ness
        self.on_text_changed("")
    def __init__(self, settings, directory, check_id_fct, annotations_path, parent=None):
        super().__init__(parent)
        # FIXME Delayed refactoring of check_id_fct and annotations_path.

        # Variables section.

        library_id = settings["libraryID"]
        library_type = settings["libraryType"]
        api_key = settings["apiKey"]
        self._zotero = ZoteroWrap(library_id, library_type, api_key, directory)

        # Widgets section.

        model = ZoteroTableModel(self._zotero, check_id_fct, annotations_path)
        model.load()

        proxy_model = QSortFilterProxyModel()
        proxy_model.setSourceModel(model)
        proxy_model.setDynamicSortFilter(True)
        proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
        proxy_model.setFilterKeyColumn(-1)  # NB: All columns.

        self.view = QTableView(self)
        self.view.setModel(proxy_model)
        self.view.setCornerButtonEnabled(False)
        self.view.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.view.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.view.setSelectionMode(QAbstractItemView.SingleSelection)
        # NB: Triggers a call to sortByColumn() which sorts by the first column.
        self.view.setSortingEnabled(True)
        self.view.setWordWrap(False)
        self.view.verticalHeader().hide()

        self.filter_edit = FilterEdit(self.view)

        # NB: The thread does not begin executing until start() is called.
        self.refresh_thread = ZoteroRefreshThread(model, self)

        # Layouts section.

        header_layout = QFormLayout()
        header_layout.addRow("Filter:", self.filter_edit)
        header_layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
        utils.configure_form_layout(header_layout)

        main_layout = QVBoxLayout()
        main_layout.addLayout(header_layout)
        main_layout.addWidget(self.view)
        self.setLayout(main_layout)

        # Signals section.

        self.filter_edit.textChanged.connect(proxy_model.setFilterFixedString)
        self.refresh_thread.started.connect(self.refresh_started)
        self.refresh_thread.finished.connect(self.refresh_finished)
Пример #18
0
	def widget_download(self):
		self.form_download_urls = QGroupBox("Download subscribed threads")
		layout = QFormLayout()

		self.button_download = self.createButton("Normal Update", self.click_process_download)
		layout.addRow(self.button_download)

		self.label_download_debug = QLabel("Press the button above to download updates to the threads you've subscribed to.")
		layout.addRow(self.label_download_debug)

		self.form_download_urls.setLayout(layout)
Пример #19
0
    def define_section2(self):
        """defining section 2: Specify allele details
        """
        mywidget = QWidget(self)
        layout = QGridLayout()
        mywidget.setLayout(layout)
        
        a1_new = False
        self.allele1_sec = AlleleSection("Allele 1:", self)
        layout.addWidget(self.allele1_sec,0,0)
        
        a2_new = False
        self.allele2_sec = AlleleSection("Allele 2:", self)
        layout.addWidget(self.allele2_sec,0,1)
        
        #ToDo: add closest alleles!
        
        button_widget = QFrame(self) # contains both-checkbox & proceed-button
        layout2 = QFormLayout()
        button_widget.setLayout(layout2)
#         self.both_cbx = QCheckBox(self)
#         self.both_cbx.clicked.connect(self.select_both)
#         self.both_lbl = QLabel("Both alleles?")
#         self.both_lbl.setStyleSheet(general.label_style_main)
#         layout2.addRow(self.both_lbl, self.both_cbx)
#         self.msg = QLabel("When selecting this option, please ensure\nyou have entered details for both alleles.")
#         self.msg.setStyleSheet(general.label_style_normal)
#         layout2.addRow(self.msg)
        layout2.addRow(QLabel("\n\n"))
        
        if a1_new:
            self.allele1_sec.checkbox.setChecked(True)
            if a2_new:
                self.allele2_sec.checkbox.setChecked(True)
        elif a2_new:
            self.allele2_sec.checkbox.setChecked(True)
#         self.allele1_sec.checkbox.clicked.connect(self.unselect_both_cbx)
        self.allele1_sec.checkbox.clicked.connect(self.unselect_other_box)
        self.allele2_sec.checkbox.clicked.connect(self.unselect_other_box)
#         self.allele2_sec.checkbox.clicked.connect(self.unselect_both_cbx)
        
        self.ok_btn = ProceedButton("Proceed", [self.allele1_sec.checkbox, self.allele2_sec.checkbox], self.log,
                                    only1 = True)
        self.ok_btn.check_ready()
        self.ok_btn.clicked.connect(self.make_ENA_file)
        self.allele1_sec.selection_changed.connect(self.ok_btn.check_ready)
        self.allele2_sec.selection_changed.connect(self.ok_btn.check_ready)
        
        layout2.addRow(self.ok_btn)
        layout.addWidget(button_widget, 0 ,3)
        layout.setColumnStretch(0,1)
        layout.setColumnStretch(1,1)
        layout.setColumnStretch(2,0)
        self.sections.append(("(2) Specify allele details:", mywidget))
Пример #20
0
 def __init__(self):
     super().__init__()
     self.setTitle(_('Selection of correct answers'))
     self.setSubTitle(_('Select the correct answers for each exam model'))
     layout = QFormLayout()
     self.setLayout(layout)
     self.tabs = QTabWidget()
     layout.addRow(self.tabs)
     self.paramNAlts = None
     self.paramNCols = None
     self.paramNPerm = None
Пример #21
0
 def __init__(self):
     super().__init__()
     self.setTitle(_('Scores for correct and incorrect answers'))
     self.setSubTitle(_('Enter the scores of correct and incorrect '
                        'answers. The program will compute scores based '
                        'on them. Setting these scores is optional.'))
     form_widget = QWidget(parent=self)
     table_widget = QWidget(parent=self)
     main_layout = QVBoxLayout(self)
     form_layout = QFormLayout(form_widget)
     table_layout = QVBoxLayout(table_widget)
     self.setLayout(main_layout)
     form_widget.setLayout(form_layout)
     table_widget.setLayout(table_layout)
     main_layout.addWidget(form_widget)
     main_layout.addWidget(table_widget)
     main_layout.setAlignment(table_widget, Qt.AlignHCenter)
     self.combo = widgets.CustomComboBox(parent=self)
     self.combo.set_items([
         _('No scores'),
         _('Same score for all the questions'),
         _('Base score plus per-question weight'),
     ])
     self.combo.currentIndexChanged.connect(self._update_combo)
     self.correct_score = widgets.InputScore(is_positive=True)
     correct_score_label = QLabel(_('Score for correct answers'))
     incorrect_score_label = QLabel(_('Score for incorrect answers'))
     blank_score_label = QLabel(_('Score for blank answers'))
     self.incorrect_score = widgets.InputScore(is_positive=False)
     self.blank_score = widgets.InputScore(is_positive=False)
     self.button_reset = QPushButton(_('Reset question weights'))
     button_defaults = QPushButton(_('Compute default scores'))
     self.weights_table = widgets.CustomTableView()
     weights_table_label = QLabel(_('Per-question score weights:'))
     form_layout.addRow(self.combo)
     form_layout.addRow(correct_score_label, self.correct_score)
     form_layout.addRow(incorrect_score_label, self.incorrect_score)
     form_layout.addRow(blank_score_label, self.blank_score)
     table_layout.addWidget(weights_table_label)
     table_layout.addWidget(self.weights_table)
     table_layout.addWidget(self.button_reset)
     table_layout.addWidget(button_defaults)
     table_layout.setAlignment(weights_table_label, Qt.AlignHCenter)
     table_layout.setAlignment(self.weights_table, Qt.AlignHCenter)
     table_layout.setAlignment(self.button_reset, Qt.AlignHCenter)
     table_layout.setAlignment(button_defaults, Qt.AlignHCenter)
     self.button_reset.clicked.connect(self._reset_weights)
     button_defaults.clicked.connect(self._compute_default_values)
     self.base_score_widgets = [
         self.correct_score, correct_score_label,
         self.incorrect_score, incorrect_score_label,
         self.blank_score, blank_score_label,
         button_defaults,
     ]
     self.weights_widgets = [
         self.weights_table, weights_table_label,
     ]
     self.current_mode = None
Пример #22
0
	def widget_register_url(self):
		self.form_register_url = QGroupBox("Register new URL")
		layout = QFormLayout()

		self.text_input_new_url = QLineEdit()
		self.button_register_url = self.createButton("Register", self.click_process_new_url)
		layout.addRow(self.button_register_url, self.text_input_new_url)

		self.label_new_url_debug = QLabel("Enter URLs here and press 'Register' to add them to your subscriptions.")
		layout.addRow(self.label_new_url_debug)

		self.form_register_url.setLayout(layout)
 def _templates_forms(templates_widgets):
     """Return the edition forms for the dict {type: {field: widget}}."""
     forms = []
     for type_widgets in templates_widgets.values():
         form = QWidget()
         layout = QFormLayout()
         for field, widget in type_widgets.items():
             layout.addRow(field + ":", widget)
         layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
         utils.configure_form_layout(layout)
         form.setLayout(layout)
         forms.append(form)
     return forms
Пример #24
0
 def init_UI(self):
     self.log.debug("Opening ChangeExtIdDialog...")
     layout = QFormLayout()
     self.setLayout(layout)
     self.title = "Change a sample's external sample ID"
     
     self.sample_ext_field = QLineEdit(self)
     self.sample_ext_field.setText(self.sample_id_ext)
     layout.addRow(QLabel("New External Sample-ID:"), self.sample_ext_field)
     
     self.ok_btn = QPushButton("Save", self)
     layout.addRow(self.ok_btn)
     self.ok_btn.clicked.connect(self.on_clicked)
Пример #25
0
    def __init__(self, mainwindow, parent=None):
        """
        Initialize the diagram scene information box.
        :type mainwindow: MainWindow
        :type parent: QWidget
        """
        super().__init__(mainwindow, parent)

        self.conceptsKey = Key('Concepts', self)
        self.conceptsField = Int(self)
        self.conceptsField.setReadOnly(True)

        self.rolesKey = Key('Roles', self)
        self.rolesField = Int(self)
        self.rolesField.setReadOnly(True)

        self.attributesKey = Key('Attributes', self)
        self.attributesField = Int(self)
        self.attributesField.setReadOnly(True)

        self.inclusionsKey = Key('Inclusions', self)
        self.inclusionsField = Int(self)
        self.inclusionsField.setReadOnly(True)

        self.membershipKey = Key('Membership', self)
        self.membershipField = Int(self)
        self.membershipField.setReadOnly(True)

        self.atomicPredHeader = Header('Atomic predicates', self)

        self.atomicPredLayout = QFormLayout()
        self.atomicPredLayout.setSpacing(0)
        self.atomicPredLayout.addRow(self.conceptsKey, self.conceptsField)
        self.atomicPredLayout.addRow(self.rolesKey, self.rolesField)
        self.atomicPredLayout.addRow(self.attributesKey, self.attributesField)

        self.assertionsHeader = Header('Assertions', self)

        self.assertionsLayout = QFormLayout()
        self.assertionsLayout.setSpacing(0)
        self.assertionsLayout.addRow(self.inclusionsKey, self.inclusionsField)
        self.assertionsLayout.addRow(self.membershipKey, self.membershipField)

        self.mainLayout = QVBoxLayout(self)
        self.mainLayout.setAlignment(Qt.AlignTop)
        self.mainLayout.setContentsMargins(0, 0, 0, 0)
        self.mainLayout.setSpacing(0)
        self.mainLayout.addWidget(self.atomicPredHeader)
        self.mainLayout.addLayout(self.atomicPredLayout)
        self.mainLayout.addWidget(self.assertionsHeader)
        self.mainLayout.addLayout(self.assertionsLayout)
Пример #26
0
    def __init__(self, *args, **kwargs):
        super(LanguagePage, self).__init__(*args, **kwargs)

        self.setTitle(self.tr("Language"))

        layout = QFormLayout()

        self.language = QLineEdit()

        layout.addRow(self.tr("Language as called in it's language"), self.language)

        self.setLayout(layout)

        self.registerField("language*", self.language)
Пример #27
0
    def __init__(self):
        super(QWidget, self).__init__()
        layout = QFormLayout()
        self.setLayout(layout)

        self.buildDependencies = QPlainTextEdit()
        self.buildDependencies.textChanged.connect(self.buildDependenciesChanged)
        self.buildDependencies.setMinimumHeight(70)
        layout.addRow('Build Dependencies', self.buildDependencies)

        self.runDependencies = QPlainTextEdit()
        self.runDependencies.textChanged.connect(self.runDependenciesChanged)
        self.runDependencies.setMinimumHeight(70)
        layout.addRow('Run Dependencies', self.runDependencies)
Пример #28
0
 def setupUi(self, PropDetailsDlg):
     PropDetailsDlg.setModal(True)
     layout = QVBoxLayout(PropDetailsDlg)
     layout.setContentsMargins(10, 15, 10, 10)
     name = QLabel("<b><i>%s</i></b>" % PropDetailsDlg.data.name)
     name.setAlignment(Qt.AlignCenter)
     layout.addWidget(name)
     body = QFormLayout()
     body.setLabelAlignment(Qt.AlignRight)
     body.setVerticalSpacing(20)
     body.setContentsMargins(25, 10, 25, 30)
     link = "<a href='%s'>%s</a>" % (PropDetailsDlg.data.URL, PropDetailsDlg.data.URL)
     link_label = QLabel(link)
     link_label.setOpenExternalLinks(True)
     body.addRow(QLabel("<b>URL: </b>"), link_label)
     body.addRow(QLabel("<b>TotalPayment: </b>"), QLabel(str(PropDetailsDlg.data.ToalPayment)))
     body.addRow(QLabel("<b>MonthlyPayment: </b>"), QLabel(str(PropDetailsDlg.data.MonthlyPayment)))
     hashLabel = self.selectable_line(PropDetailsDlg.data.Hash)
     body.addRow(QLabel("<b>Hash: </b>"), hashLabel)
     feeHashLabel = self.selectable_line(PropDetailsDlg.data.FeeHash)
     body.addRow(QLabel("<b>FeeHash: </b>"), feeHashLabel)
     body.addRow(QLabel("<b>BlockStart: </b>"), QLabel(str(PropDetailsDlg.data.BlockStart)))
     body.addRow(QLabel("<b>BlockEnd: </b>"), QLabel(str(PropDetailsDlg.data.BlockEnd)))
     body.addRow(QLabel("<b>TotalPayCount: </b>"), QLabel(str(PropDetailsDlg.data.TotalPayCount)))
     body.addRow(QLabel("<b>RemainingPayCount: </b>"), QLabel(str(PropDetailsDlg.data.RemainingPayCount)))
     addyLabel = self.selectable_line(PropDetailsDlg.data.PaymentAddress)
     body.addRow(QLabel("<b>PaymentAddress: </b>"), addyLabel)
     votes = "<span style='color: green'>%d YEAS</span> / " % PropDetailsDlg.data.Yeas
     votes += "<span style='color: orange'>%d ABSTAINS</span> / " % PropDetailsDlg.data.Abstains
     votes += "<span style='color: red'>%d NAYS</span>" % PropDetailsDlg.data.Nays
     body.addRow(QLabel("<b>Votes: </b>"), QLabel(votes))
     my_yeas = ["%s <em style='color: green'>(%s)</em>" % (x[0], strftime('%Y-%m-%d %H:%M:%S',
                                                     gmtime(x[1]))) for x in PropDetailsDlg.myYeas]
     body.addRow(QLabel("<b>My Yeas: </b>"), self.scroll(my_yeas))
     my_abstains = ["%s <em style='color: orange'>(%s)</em>" % (x[0], strftime('%Y-%m-%d %H:%M:%S',
                                                     gmtime(x[1]))) for x in PropDetailsDlg.myAbstains]
     body.addRow(QLabel("<b>My Abstains: </b>"), self.scroll(my_abstains))
     my_nays = ["%s <em style='color: red'>(%s)</em>" % (x[0], strftime('%Y-%m-%d %H:%M:%S',
                                                     gmtime(x[1]))) for x in PropDetailsDlg.myNays]
     body.addRow(QLabel("<b>My Nays: </b>"), self.scroll(my_nays))
     layout.addLayout(body)
     self.okButton = QPushButton('OK')
     self.okButton.clicked.connect(self.accept)
     layout.addWidget(self.okButton)
     sh = layout.sizeHint()
     self.setFixedSize(sh)
    def initUI(self):
        pg.setConfigOption('background', 'w')
        self.actual_dir = os.getcwd()
        self.lblTit = pg.LabelItem(justify='right')

        #        self.lblTit.setText("Hola")
        #Variables
        self.data_dir = ''
        self.result_dir = ''
        self.nom_dir = []
        self.nom_arch = []
        self.nom_facil = []
        self.sizes = np.asarray([120, 60, 30, 15, 7.5, 3.75, 1.875, 0.9375])

        buttons = QHBoxLayout()
        datos = QVBoxLayout()
        contain = QSplitter(Qt.Horizontal)
        ima = QVBoxLayout()

        self.glw = pg.GraphicsLayoutWidget(border=(100, 100, 100))
        self.glw.useOpenGL(True)
        self.glw.addItem(self.lblTit, col=1, colspan=4)
        self.glw.nextRow()
        self.glw.addLabel('Canales', angle=-90, rowspan=3)

        vtick = QPainterPath()
        vtick.moveTo(0, -0.5)
        vtick.lineTo(0, 0.5)
        vtick.addRect(0, 0.5, 1, 1)

        s1 = pg.ScatterPlotItem(pxMode=False)
        s1.setSymbol(vtick)
        s1.setSize(1)

        s2 = pg.ScatterPlotItem(pxMode=False)
        s2.setSymbol(vtick)
        s2.setSize(1)

        s3 = pg.ScatterPlotItem(pxMode=False)
        s3.setSymbol(vtick)
        s3.setSize(1)
        #        s3.setPen=(QColor(*np.random.randint(0, 255 + 1, 3).tolist()))

        s4 = pg.ScatterPlotItem(pxMode=False)
        s4.setSymbol(vtick)
        s4.setSize(1)

        s5 = pg.ScatterPlotItem(pxMode=False)
        s5.setSymbol(vtick)
        s5.setSize(1)

        s6 = pg.ScatterPlotItem(pxMode=False)
        s6.setSymbol(vtick)
        s6.setSize(1)

        s7 = pg.ScatterPlotItem(pxMode=False)
        s7.setSymbol(vtick)
        s7.setSize(1)

        s8 = pg.ScatterPlotItem(pxMode=False)
        s8.setSymbol(vtick)
        s8.setSize(1)

        s9 = pg.ScatterPlotItem(pxMode=False)
        s9.setSymbol(vtick)
        s9.setSize(1)

        s10 = pg.ScatterPlotItem(pxMode=False)
        s10.setSymbol(vtick)
        s10.setSize(1)

        s11 = pg.ScatterPlotItem(pxMode=False)
        s11.setSymbol(vtick)
        s11.setSize(1)

        s12 = pg.ScatterPlotItem(pxMode=False)
        s12.setSymbol(vtick)
        s12.setSize(1)

        s13 = pg.ScatterPlotItem(pxMode=False)
        s13.setSymbol(vtick)
        s13.setSize(1)

        s14 = pg.ScatterPlotItem(pxMode=False)
        s14.setSymbol(vtick)
        s14.setSize(1)

        s15 = pg.ScatterPlotItem(pxMode=False)
        s15.setSymbol(vtick)
        s15.setSize(1)

        s16 = pg.ScatterPlotItem(pxMode=False)
        s16.setSymbol(vtick)
        s16.setSize(1)

        s17 = pg.ScatterPlotItem(pxMode=False)
        s17.setSymbol(vtick)
        s17.setSize(1)

        s18 = pg.ScatterPlotItem(pxMode=False)
        s18.setSymbol(vtick)
        s18.setSize(1)

        s19 = pg.ScatterPlotItem(pxMode=False)
        s19.setSymbol(vtick)
        s19.setSize(1)

        s20 = pg.ScatterPlotItem(pxMode=False)
        s20.setSymbol(vtick)
        s20.setSize(1)

        s21 = pg.ScatterPlotItem(pxMode=False)
        s21.setSymbol(vtick)
        s21.setSize(1)

        s22 = pg.ScatterPlotItem(pxMode=False)
        s22.setSymbol(vtick)
        s22.setSize(1)

        y = [
            '0', 'EMG', 'ROG', 'LOG', 'T6', 'T5', 'T4', 'T3', 'PZ', 'P4', 'P3',
            'O2', 'O1', 'FZ', 'FP2', 'FP1', 'F8', 'F7', 'F4', 'F3', 'CZ', 'C4',
            'C3'
        ]
        ydict = dict(enumerate(y))
        stringaxis = pg.AxisItem(orientation='left')
        stringaxis.setTicks([ydict.items()])

        self.p1 = self.glw.addPlot(axisItems={'left': stringaxis},
                                   row=1,
                                   col=1)

        #        self.p2 = self.glw.addPlot(col=0)

        #        self.p1.setYRange(-0.5, 26.5, padding=0)
        self.p1.setLimits(yMin=-0.5)
        self.p1.setLimits(yMax=26.5)

        self.p1.addItem(s1)
        self.p1.addItem(s2)
        self.p1.addItem(s3)
        self.p1.addItem(s4)
        self.p1.addItem(s5)
        self.p1.addItem(s6)
        self.p1.addItem(s7)
        self.p1.addItem(s8)
        self.p1.addItem(s9)
        self.p1.addItem(s10)
        self.p1.addItem(s11)
        self.p1.addItem(s12)
        self.p1.addItem(s13)
        self.p1.addItem(s14)
        self.p1.addItem(s15)
        self.p1.addItem(s16)
        self.p1.addItem(s17)
        self.p1.addItem(s18)
        self.p1.addItem(s19)
        self.p1.addItem(s20)
        self.p1.addItem(s21)
        self.p1.addItem(s22)

        self.spis = [
            s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15,
            s16, s17, s18, s19, s20, s21, s22
        ]

        self.lytEpoch = QFormLayout()
        self.cmbEpoch = QComboBox()
        self.cmbEpoch.addItem("120")
        self.cmbEpoch.addItem("60")
        self.cmbEpoch.addItem("30")
        self.cmbEpoch.addItem("15")
        self.cmbEpoch.addItem("7.5")
        self.cmbEpoch.addItem("3.75")
        self.cmbEpoch.addItem("1.875")
        self.cmbEpoch.addItem("0.9375")

        self.lytEpoch.addRow("Epoch size: ", self.cmbEpoch)

        btn_data_dir = QPushButton('Load Files')
        btn_data_dir.clicked.connect(lambda: self.openFiles(1))

        btn_result_dir = QPushButton('Save Results')
        btn_result_dir.clicked.connect(lambda: self.openFiles(2))

        btn_do = QPushButton('Do')
        btn_do.clicked.connect(self.llenarTabla)

        self.table = QTableWidget()

        btn_make = QPushButton('Processing')
        btn_make.clicked.connect(self.showDialog)

        btn_showSujeto = QPushButton('Sujeto')
        btn_showSujeto.clicked.connect(self.recuperaSujeto)

        datos.addLayout(self.lytEpoch)
        buttons.addWidget(btn_data_dir)
        buttons.addWidget(btn_result_dir)
        buttons.addWidget(btn_do)
        datos.addLayout(buttons)
        datos.addWidget(self.table)
        datos.addWidget(btn_make)
        datos.addWidget(btn_showSujeto)
        ima.addWidget(self.glw)

        bot = QWidget()
        bot.setLayout(datos)
        gra = QWidget()
        gra.setLayout(ima)

        contain.addWidget(bot)
        contain.addWidget(gra)
        self.addWidget(contain)
Пример #30
0
    def __init__(self):
        super().__init__()
        self.main_widget = QWidget()
        self.main_widget.setGeometry(450, 100, 950, 800)
        self.main_widget.setWindowTitle("MULTI-STIMULI PROCESS")
        self.main_widget.setFont((QFont("Amble", 11)))
        self.main_widget.setFixedSize(1000, 650)
        # self.main_widget.setMinimumSize(900, 900)
        # self.main_widget.setMaximumSize(900, 600)

        # CREATING SELECTIONS...

        self.stimodour1 = QCheckBox()
        self.stimodour2 = QCheckBox()
        self.whisker = QCheckBox()
        self.auditory = QCheckBox()
        self.visual = QCheckBox()
        self.check_list = [
            self.stimodour1, self.stimodour2, self.whisker, self.auditory,
            self.visual
        ]
        self.odour1_flag = 0  # Creating check flag for experiments
        self.odour2_flag = 0
        self.whisker_flag = 0
        self.auditory_flag = 0
        self.visual_flag = 0
        # CREATING GUI...

        self.titlebox = QHBoxLayout()
        self.gap = QLabel("")
        self.types = QLabel("Types of Stimulations")
        self.types.setFont(QFont("Amble", 11, QFont.Bold))
        self.types.setAlignment(Qt.AlignLeft)
        self.delay = QLabel("Delay")
        self.delay.setFont(QFont("Amble", 11, QFont.Bold))
        self.delay.setAlignment(Qt.AlignHCenter)
        self.stim_length = QLabel("Length of Stim")
        self.stim_length.setFont(QFont("Amble", 11, QFont.Bold))
        self.stim_length.setAlignment(Qt.AlignCenter)
        self.offtime = QLabel("Off Time")
        self.offtime.setFont(QFont("Amble", 11, QFont.Bold))
        self.offtime.setAlignment(Qt.AlignHCenter)
        self.frequency = QLabel("Frequency")
        self.frequency.setFont(QFont("Amble", 11, QFont.Bold))
        self.frequency.setAlignment(Qt.AlignHCenter)
        self.amplitude = QLabel("Amplitude")
        self.amplitude.setFont(QFont("Amble", 11, QFont.Bold))
        self.amplitude.setAlignment(Qt.AlignHCenter)
        self.repetition = QLabel("Repetition")
        self.repetition.setFont(QFont("Amble", 11, QFont.Bold))
        self.repetition.setAlignment(Qt.AlignHCenter)

        # CREATING GUI...

        self.titlebox.addWidget(self.types)
        self.titlebox.addWidget(self.delay)
        self.titlebox.addWidget(self.stim_length)
        self.titlebox.addWidget(self.offtime)
        self.titlebox.addWidget(self.frequency)
        self.titlebox.addWidget(self.amplitude)
        self.titlebox.addWidget(self.repetition)

        # CREATING GUI...

        self.boxodour1 = QHBoxLayout()
        self.odour1 = QLabel("   Odour 1")
        self.odour1.setFont(QFont("Amble", 11))
        self.odour2 = QLabel("   Odour 2")
        self.odour2.setFont(QFont("Amble", 11))
        self.odour1buton1 = QSpinBox()
        self.odour1buton2 = QSpinBox()
        self.odour1buton3 = QSpinBox()
        self.odour1buton4 = QSpinBox()
        self.odour1buton5 = QDoubleSpinBox()
        self.odour1buton6 = QSpinBox()
        self.odour1buton4.setEnabled(0)
        self.odour1buton5.setEnabled(0)

        self.boxodour1.addWidget(self.odour1)
        self.boxodour1.addWidget(self.odour1buton1)
        self.boxodour1.addWidget(self.odour1buton2)
        self.boxodour1.addWidget(self.odour1buton3)
        self.boxodour1.addWidget(self.odour1buton4)
        self.boxodour1.addWidget(self.odour1buton5)
        self.boxodour1.addWidget(self.odour1buton6)

        # CREATING GUI...

        self.odour2buton1 = QSpinBox()
        self.odour2buton2 = QSpinBox()
        self.odour2buton3 = QSpinBox()
        self.odour2buton4 = QSpinBox()
        self.odour2buton5 = QDoubleSpinBox()
        self.odour2buton6 = QSpinBox()
        self.odour2buton4.setEnabled(0)
        self.odour2buton5.setEnabled(0)

        self.boxodour2 = QHBoxLayout()
        self.boxodour2.addWidget(self.odour2)
        self.boxodour2.addWidget(self.odour2buton1)
        self.boxodour2.addWidget(self.odour2buton2)
        self.boxodour2.addWidget(self.odour2buton3)
        self.boxodour2.addWidget(self.odour2buton4)
        self.boxodour2.addWidget(self.odour2buton5)
        self.boxodour2.addWidget(self.odour2buton6)

        # CREATING GUI...

        self.boxwhisker = QHBoxLayout()
        self.label2 = QLabel("   Whisker")
        self.label2.setFont(QFont("Amble", 11))
        self.buton2 = QSpinBox()
        self.buton6 = QSpinBox()
        self.buton9 = QSpinBox()
        self.buton12 = QSpinBox()
        self.buton15 = QDoubleSpinBox()
        self.buton18 = QSpinBox()

        self.boxwhisker.addWidget(self.label2)
        self.boxwhisker.addWidget(self.buton2)
        self.boxwhisker.addWidget(self.buton6)
        self.boxwhisker.addWidget(self.buton9)
        self.boxwhisker.addWidget(self.buton12)
        self.boxwhisker.addWidget(self.buton15)
        self.boxwhisker.addWidget(self.buton18)

        # CREATING GUI...

        self.box_auditory = QHBoxLayout()
        self.label3 = QLabel("   Auditory")
        self.label3.setFont(QFont("Amble", 11))
        self.buton3 = QSpinBox()
        self.buton7 = QSpinBox()
        self.buton10 = QSpinBox()
        self.buton13 = QSpinBox()
        self.buton16 = QDoubleSpinBox()
        self.buton19 = QSpinBox()

        self.box_auditory.addWidget(self.label3)
        self.box_auditory.addWidget(self.buton3)
        self.box_auditory.addWidget(self.buton7)
        self.box_auditory.addWidget(self.buton10)
        self.box_auditory.addWidget(self.buton13)
        self.box_auditory.addWidget(self.buton16)
        self.box_auditory.addWidget(self.buton19)

        # CREATING GUI...

        self.visual_box = QHBoxLayout()
        self.label4 = QLabel("   Visual")
        self.label4.setFont(QFont("Amble", 11))
        self.buton4 = QSpinBox()
        self.buton8 = QSpinBox()
        self.buton11 = QSpinBox()
        self.buton14 = QSpinBox()
        self.buton17 = QDoubleSpinBox()
        self.buton20 = QSpinBox()

        self.butonlist = [
            self.odour1buton1, self.odour1buton2, self.odour1buton3,
            self.odour1buton6, self.odour2buton1, self.odour2buton2,
            self.odour2buton3, self.odour2buton6, self.buton2, self.buton6,
            self.buton9, self.buton12, self.buton15, self.buton18, self.buton3,
            self.buton7, self.buton10, self.buton13, self.buton16,
            self.buton19, self.buton4, self.buton8, self.buton11, self.buton14,
            self.buton17, self.buton20
        ]

        self.visual_box.addWidget(self.label4)
        self.visual_box.addWidget(self.buton4)
        self.visual_box.addWidget(self.buton8)
        self.visual_box.addWidget(self.buton11)
        self.visual_box.addWidget(self.buton14)
        self.visual_box.addWidget(self.buton17)
        self.visual_box.addWidget(self.buton20)

        # CREATING START-CANCEL BUTTONS

        self.boxofcontrol = QHBoxLayout()
        self.start = QPushButton("START")
        self.start.setFixedSize(100, 28)
        self.cancel = QPushButton("CANCEL")
        self.cancel.setFixedSize(100, 28)
        self.cancel.clicked.connect(self.click_cancel)
        self.start.clicked.connect(self.function_start)
        self.boxofcontrol.addWidget(self.start)
        self.boxofcontrol.addWidget(self.cancel)

        # LAYOUT of BOXES (RELATED TO GUI)

        self.form = QFormLayout()
        self.form.addRow(self.gap)
        self.form.addRow(self.titlebox)
        self.form.addRow(self.gap)
        self.form.addRow(self.stimodour1, self.boxodour1)
        self.form.addRow(self.gap)
        self.form.addRow(self.stimodour2, self.boxodour2)
        self.form.addRow(self.gap)
        self.form.addRow(self.whisker, self.boxwhisker)
        self.form.addRow(self.gap)
        self.form.addRow(self.visual, self.box_auditory)
        self.form.addRow(self.gap)
        self.form.addRow(self.auditory, self.visual_box)
        self.form.addRow(self.gap)
        self.form.addRow(self.gap)
        self.form.addRow(self.gap)
        self.form.addRow(self.gap)
        self.form.addRow(self.boxofcontrol)
        self.main_widget.setLayout(self.form)
        self.finished_signal.connect(self.plotting_figure)

        self.main_widget.show()
Пример #31
0
class EntryEditDialog(QDialog):
    GROUP_NAME = ''
    ORGANIZATION_NAME = ''

    def __init__(self, person, is_new=False):
        super().__init__(GlobalAccess().get_main_window())
        self.is_ok = {}
        assert (isinstance(person, Person))
        self.current_object = person
        self.is_new = is_new

        self.time_format = 'hh:mm:ss'
        time_accuracy = race().get_setting('time_accuracy', 0)
        if time_accuracy:
            self.time_format = 'hh:mm:ss.zzz'

    def exec(self):
        self.init_ui()
        self.set_values_from_model()
        return super().exec()

    def init_ui(self):
        self.setWindowTitle(_('Entry properties'))
        self.setWindowIcon(QIcon(config.ICON))
        self.setSizeGripEnabled(False)
        self.setModal(True)

        self.layout = QFormLayout(self)
        self.label_surname = QLabel(_('Last name'))
        self.item_surname = QLineEdit()
        self.layout.addRow(self.label_surname, self.item_surname)

        self.label_name = QLabel(_('First name'))
        self.item_name = AdvComboBox()
        self.item_name.addItems(get_names())
        self.layout.addRow(self.label_name, self.item_name)

        self.label_group = QLabel(_('Group'))
        self.item_group = AdvComboBox()
        self.item_group.addItems(get_race_groups())
        self.layout.addRow(self.label_group, self.item_group)

        self.label_team = QLabel(_('Team'))
        self.item_team = AdvComboBox()
        self.item_team.addItems(get_race_teams())
        self.layout.addRow(self.label_team, self.item_team)

        use_birthday = Config().configuration.get('use_birthday', False)
        if use_birthday:
            self.label_birthday = QLabel(_('Birthday'))
            self.item_birthday = QDateEdit()
            self.item_birthday.setObjectName('BirthdayDateEdit')
            self.item_birthday.setDate(date.today())
            self.item_birthday.setMaximumDate(date.today())
            self.layout.addRow(self.label_birthday, self.item_birthday)
        else:
            self.label_year = QLabel(_('Year of birth'))
            self.item_year = QSpinBox()
            self.item_year.setObjectName('YearSpinBox')
            self.item_year.setMinimum(0)
            self.item_year.setMaximum(date.today().year)
            self.item_year.editingFinished.connect(self.year_change)
            self.layout.addRow(self.label_year, self.item_year)

        self.label_qual = QLabel(_('Qualification'))
        self.item_qual = AdvComboBox()
        for i in list(Qualification):
            self.item_qual.addItem(i.get_title())
        self.layout.addRow(self.label_qual, self.item_qual)

        self.is_ok['bib'] = True
        self.label_bib = QLabel(_('Bib'))
        self.item_bib = QSpinBox()
        self.item_bib.setMinimum(0)
        self.item_bib.setMaximum(Limit.BIB)
        self.item_bib.valueChanged.connect(self.check_bib)
        self.layout.addRow(self.label_bib, self.item_bib)

        self.label_bib_info = QLabel('')
        self.layout.addRow(QLabel(''), self.label_bib_info)

        self.label_start = QLabel(_('Start time'))
        self.item_start = QTimeEdit()
        self.item_start.setDisplayFormat(self.time_format)
        self.layout.addRow(self.label_start, self.item_start)

        self.label_start_group = QLabel(_('Start group'))
        self.item_start_group = QSpinBox()
        self.item_start_group.setMinimum(0)
        self.item_start_group.setMaximum(99)
        self.layout.addRow(self.label_start_group, self.item_start_group)

        self.is_ok['card'] = True
        self.label_card = QLabel(_('Punch card #'))
        self.item_card = QSpinBox()
        self.item_card.setMinimum(0)
        self.item_card.setMaximum(9999999)
        self.item_card.valueChanged.connect(self.check_card)
        self.layout.addRow(self.label_card, self.item_card)

        self.label_card_info = QLabel('')
        self.layout.addRow(QLabel(''), self.label_card_info)

        self.item_rented = QCheckBox(_('rented card'))
        self.item_paid = QCheckBox(_('is paid'))
        self.item_out_of_competition = QCheckBox(_('out of competition'))
        self.item_personal = QCheckBox(_('personal participation'))
        self.layout.addRow(self.item_rented, self.item_out_of_competition)
        self.layout.addRow(self.item_paid, self.item_personal)

        self.label_comment = QLabel(_('Comment'))
        self.item_comment = QTextEdit()
        self.item_comment.setTabChangesFocus(True)
        self.layout.addRow(self.label_comment, self.item_comment)

        def cancel_changes():
            self.close()

        def apply_changes():
            try:
                self.apply_changes_impl()
            except Exception as e:
                logging.error(str(e))
            self.close()

        button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                      | QDialogButtonBox.Cancel)
        self.button_ok = button_box.button(QDialogButtonBox.Ok)
        self.button_ok.setText(_('OK'))
        self.button_ok.clicked.connect(apply_changes)
        self.button_cancel = button_box.button(QDialogButtonBox.Cancel)
        self.button_cancel.setText(_('Cancel'))
        self.button_cancel.clicked.connect(cancel_changes)
        self.layout.addRow(button_box)

        self.show()

    def year_change(self):
        """
        Convert 2 digits of year to 4
        2 -> 2002
        11 - > 2011
        33 -> 1933
        56 -> 1956
        98 - > 1998
        0 -> 0 exception!
        """
        widget = self.sender()
        assert isinstance(widget, QSpinBox)
        year = widget.value()
        if 0 < year < 100:
            cur_year = date.today().year
            new_year = cur_year - cur_year % 100 + year
            if new_year > cur_year:
                new_year -= 100
            widget.setValue(new_year)

    def items_ok(self):
        ret = True
        for item_name in self.is_ok.keys():
            if self.is_ok[item_name] is not True:
                ret = False
                break
        return ret

    def check_bib(self):
        bib = self.item_bib.value()
        self.label_bib_info.setText('')
        if bib:
            person = find(race().persons, bib=bib)
            if person:
                if person.bib == self.current_object.bib:
                    self.button_ok.setEnabled(True)
                    return
                self.button_ok.setDisabled(True)
                self.is_ok['bib'] = False
                info = '{}\n{}'.format(_('Number already exists'),
                                       person.full_name)
                if person.group:
                    info = '{}\n{}: {}'.format(info, _('Group'),
                                               person.group.name)
                self.label_bib_info.setText(info)
            else:
                self.label_bib_info.setText(_('Number is unique'))
                self.is_ok['bib'] = True
                if self.items_ok():
                    self.button_ok.setEnabled(True)
        else:
            self.button_ok.setEnabled(True)

    def check_card(self):
        number = self.item_card.value()
        self.label_card_info.setText('')
        if number:
            person = None
            for _p in race().persons:
                if _p.card_number and _p.card_number == number:
                    person = _p
                    break
            if person:
                if person.card_number == self.current_object.card_number:
                    self.button_ok.setEnabled(True)
                    return
                self.button_ok.setDisabled(True)
                self.is_ok['card'] = False
                info = '{}\n{}'.format(_('Card number already exists'),
                                       person.full_name)
                if person.group:
                    info = '{}\n{}: {}'.format(info, _('Group'),
                                               person.group.name)
                if person.bib:
                    info = '{}\n{}: {}'.format(info, _('Bib'), person.bib)
                self.label_card_info.setText(info)
            else:
                self.label_card_info.setText(_('Card number is unique'))
                self.is_ok['card'] = True
                if self.items_ok():
                    self.button_ok.setEnabled(True)
        else:
            self.button_ok.setEnabled(True)

    def set_values_from_model(self):
        self.item_surname.setText(self.current_object.surname)
        self.item_surname.selectAll()
        self.item_name.setCurrentText(self.current_object.name)
        if self.current_object.group is not None:
            self.item_group.setCurrentText(self.current_object.group.name)
        else:
            self.item_group.setCurrentText(self.GROUP_NAME)
        if self.current_object.organization is not None:
            self.item_team.setCurrentText(
                self.current_object.organization.name)
        else:
            self.item_team.setCurrentText(self.ORGANIZATION_NAME)
        if self.current_object.qual:
            self.item_qual.setCurrentText(self.current_object.qual.get_title())
        if self.current_object.bib:
            self.item_bib.setValue(int(self.current_object.bib))
        if self.current_object.start_time is not None:
            time = time_to_qtime(self.current_object.start_time)
            self.item_start.setTime(time)
        if self.current_object.start_group is not None:
            self.item_start_group.setValue(int(
                self.current_object.start_group))

        if self.current_object.card_number:
            self.item_card.setValue(self.current_object.card_number)

        self.item_out_of_competition.setChecked(
            self.current_object.is_out_of_competition)
        self.item_paid.setChecked(self.current_object.is_paid)
        self.item_paid.setChecked(self.current_object.is_paid)
        self.item_personal.setChecked(self.current_object.is_personal)
        self.item_rented.setChecked(self.current_object.is_rented_card)

        self.item_comment.setText(self.current_object.comment)

        use_birthday = Config().configuration.get('use_birthday', False)
        if use_birthday:
            if self.current_object.birth_date:
                self.item_birthday.setDate(self.current_object.birth_date)
        else:
            if self.current_object.get_year():
                self.item_year.setValue(self.current_object.get_year())

    def apply_changes_impl(self):
        person = self.current_object
        assert (isinstance(person, Person))
        if self.is_new:
            race().persons.insert(0, person)
        if person.name != self.item_name.currentText():
            person.name = self.item_name.currentText()
        if person.surname != self.item_surname.text():
            person.surname = self.item_surname.text()
        if (person.group is not None and person.group.name != self.item_group.currentText()) or\
                (person.group is None and len(self.item_group.currentText()) > 0):
            person.group = find(race().groups,
                                name=self.item_group.currentText())
        if (person.organization is not None and person.organization.name != self.item_team.currentText()) or \
                (person.organization is None and len(self.item_team.currentText()) > 0):
            organization = find(race().organizations,
                                name=self.item_team.currentText())
            if organization is None:
                organization = Organization()
                organization.name = self.item_team.currentText()
                race().organizations.append(organization)
                Teamwork().send(organization.to_dict())
            person.organization = organization
        if person.qual.get_title() != self.item_qual.currentText():
            person.qual = Qualification.get_qual_by_name(
                self.item_qual.currentText())
        if person.bib != self.item_bib.value():
            person.bib = self.item_bib.value()

        new_time = time_to_otime(self.item_start.time())
        if person.start_time != new_time:
            person.start_time = new_time

        if person.start_group != self.item_start_group.value(
        ) and self.item_start_group.value():
            person.start_group = self.item_start_group.value()

        if (not person.card_number or int(person.card_number) != self.item_card.value()) \
                and self.item_card.value:
            race().person_card_number(person, self.item_card.value())

        if person.is_out_of_competition != self.item_out_of_competition.isChecked(
        ):
            person.is_out_of_competition = self.item_out_of_competition.isChecked(
            )

        if person.is_paid != self.item_paid.isChecked():
            person.is_paid = self.item_paid.isChecked()

        if person.is_rented_card != self.item_rented.isChecked():
            person.is_rented_card = self.item_rented.isChecked()

        if person.is_personal != self.item_personal.isChecked():
            person.is_personal = self.item_personal.isChecked()

        if person.comment != self.item_comment.toPlainText():
            person.comment = self.item_comment.toPlainText()

        use_birthday = Config().configuration.get('use_birthday', False)
        if use_birthday:
            new_birthday = qdate_to_date(self.item_birthday.date())
            if person.birth_date != new_birthday and new_birthday:
                if person.birth_date or new_birthday != date.today():
                    person.birth_date = new_birthday
        else:
            if person.get_year() != self.item_year.value():
                person.set_year(self.item_year.value())

        ResultCalculation(race()).process_results()
        GlobalAccess().get_main_window().refresh()
        Teamwork().send(person.to_dict())
Пример #32
0
class PluginConfigDialog(QDialog):
    class WidgetWrapper:
        """ Wraps a widget (e.g. QLineEdit, QCheckbox, etc.) and enhances it with a validate and onChange method. """
        def __init__(self, option: PluginConfig.Option.Base, widget,
                     get_value_callback, config, on_change_signal):
            self.name = option.name
            self.widget = widget
            self.config = config
            self._get_value_callback = get_value_callback
            self.validate = lambda codec, input: self.config.validate(
                option, codec, input)
            self.onChange = on_change_signal

        def _get_value(self):
            return self._get_value_callback()

        value = property(_get_value)

    def __init__(self, context, config, title, codec, icon=None):
        super(PluginConfigDialog, self).__init__()
        self._context = context
        self.config = config
        self._codec = codec
        self._input = None
        self._widgets = {}
        self.setLayout(self._init_main_layout())
        self._build()
        self._init_shortcuts()
        self._validate()
        self.setWindowTitle(title)
        if icon:
            self.setWindowIcon(icon)

    def _init_main_layout(self):
        main_layout = QVBoxLayout()
        main_layout.addWidget(self._init_input_frame())
        main_layout.addWidget(self._init_error_frame())
        self._btn_box = self._init_button_box()
        main_layout.addWidget(self._btn_box)
        return main_layout

    def _init_error_frame(self):
        self._error_frame = QFrame()
        layout = QVBoxLayout()
        self._error_text = QLabel("")
        self._error_text.setStyleSheet('QLabel { color: red }')
        layout.addWidget(self._error_text)
        self._error_frame.setLayout(layout)
        self._error_frame.setHidden(True)
        return self._error_frame

    def _init_button_box(self):
        button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                      | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        return button_box

    def _init_shortcuts(self):
        def _accept(self):
            if self._btn_box(QDialogButtonBox.Ok).isEnabled():
                self.accept()

        ctrl_return_shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Return),
                                         self)
        ctrl_return_shortcut.activated.connect(_accept)
        alt_return_shortcut = QShortcut(QKeySequence(Qt.ALT + Qt.Key_Return),
                                        self)
        alt_return_shortcut.activated.connect(_accept)
        alt_o_shortcut = QShortcut(QKeySequence(Qt.ALT + Qt.Key_O), self)
        alt_o_shortcut.activated.connect(_accept)

    def _init_input_frame(self):
        input_frame = QGroupBox()
        self._input_frame_layout = QFormLayout()
        input_frame.setLayout(self._input_frame_layout)
        return input_frame

    def _on_change(self):
        """ Update and validate options. """
        self.config.update(
            {key: self._widgets[key].value
             for key in self.config.keys()})
        self._btn_box.button(QDialogButtonBox.Ok).setEnabled(self._validate())

    def _validate(self):
        """ Validate the current settings. """
        self._reset_errors()
        for key, widget_wrapper in self._widgets.items():
            message = widget_wrapper.validate(self._codec, self._input)
            if message is not True:
                self._show_error_indicator(widget_wrapper)
                self._show_error_message(message)
                return False

        message = self._try_codec()
        if message:
            self._show_error_message(message)
            return False

        return True

    def _try_codec(self):
        """ Tries to run the codec with the specified input. Either returns None or an error message."""
        try:
            self._codec(self.config, self._input)
        except BaseException as e:
            return str(e)

    def _reset_errors(self):
        """ Hides error message box and resets any error indicators. """
        self._error_frame.setHidden(True)
        self._error_text.setText("")
        for name in self.config.keys():
            self._reset_error(self._widgets[name])

    def _reset_error(self, widget_wrapper):
        """
        Resets any error indication on a specific widget.
        This method can be overwritten to allow customizing visualization of errors for specific widgets.
        """
        widget = widget_wrapper.widget
        if isinstance(widget, QLineEdit):
            widget.setStyleSheet('QLineEdit { }')

    def _show_error_indicator(self, widget_wrapper):
        """
        Indicates an error on a specific widget.
        This method can be overwritten to allow customizing visualization of errors for specific widgets.
        """
        widget = widget_wrapper.widget
        if isinstance(widget, QLineEdit):
            widget.setStyleSheet('QLineEdit { color: red }')

    def _show_error_message(self, message):
        """ Shows an error message within a error-box. """
        self._error_frame.setHidden(False)
        self._error_text.setText(message)

    def _build_option(self, option: PluginConfig.Option.Base) -> WidgetWrapper:
        """
        Automatically build the widget for this option.
        This method can be overwritten to allow building custom widgets.
        :return the widget for this option.
        """
        if isinstance(option, PluginConfig.Option.String):
            x = QLineEdit(option.value)
            w = PluginConfigDialog.WidgetWrapper(option, x, x.text,
                                                 self.config, x.textChanged)
            w.onChange.connect(lambda evt: self._on_change())
        elif isinstance(option, PluginConfig.Option.Integer):
            x = QLineEdit(option.value)
            w = PluginConfigDialog.WidgetWrapper(option, x, x.text,
                                                 self.config, x.textChanged)
            w.onChange.connect(lambda evt: self._on_change())
        elif isinstance(option, PluginConfig.Option.Group):
            x = QRadioButton(option.name)
            x.setChecked(option.value)
            w = PluginConfigDialog.WidgetWrapper(option, x, x.isChecked,
                                                 self.config, x.clicked)
            w.onChange.connect(lambda evt: self._on_change())
        elif isinstance(option, PluginConfig.Option.Boolean):
            x = QCheckBox(option.name)
            x.setChecked(option.value)
            w = PluginConfigDialog.WidgetWrapper(option, x, x.isChecked,
                                                 self.config, x.clicked)
            w.onChange.connect(lambda evt: self._on_change())
        else:
            raise Exception("Invalid option of type {} detected!".format(
                type(option)))
        return w

    def _add_option_widget(self, label: QLabel, widget):
        self._input_frame_layout.addRow(label, widget)

    def _build(self):
        """
        Automatically build the widgets for all options.
        This method can be overwritten to allow building custom widgets.
        """
        for key, option in self.config.items():
            label = QLabel()
            if not isinstance(option, PluginConfig.Option.Boolean):
                label.setText(option.name)
            self._widgets[key] = self._build_option(option)
            self._add_option_widget(label, self._widgets[key].widget)

    def setInput(self, text):
        self._input = text
        self._on_change()
Пример #33
0
 def _init_input_frame(self):
     input_frame = QGroupBox()
     self._input_frame_layout = QFormLayout()
     input_frame.setLayout(self._input_frame_layout)
     return input_frame
Пример #34
0
 def setupUi(self, MnStatusDlg):
     MnStatusDlg.setModal(True)
     layout = QVBoxLayout(MnStatusDlg)
     layout.setContentsMargins(10, 15, 10, 10)
     name = QLabel("<b><i>%s</i></b>" % self.mnAlias)
     name.setAlignment(Qt.AlignCenter)
     layout.addWidget(name)
     body = QFormLayout()
     body.setLabelAlignment(Qt.AlignRight)
     body.setVerticalSpacing(20)
     body.setContentsMargins(25, 10, 25, 30)
     body.addRow(QLabel("<b>Address</b>"), QLabel(self.statusData['addr']))
     body.addRow(
         QLabel("<b>Tx Hash: idx</b>"),
         QLabel(self.statusData['txhash'] + ": " +
                str(self.statusData['outidx'])))
     body.addRow(QLabel("<b>Network</b>"),
                 QLabel(self.statusData['network']))
     body.addRow(QLabel("<b>Version</b>"),
                 QLabel(str(self.statusData['version'])))
     body.addRow(QLabel("<b>Rank</b>"),
                 QLabel(str(self.statusData['rank'])))
     body.addRow(QLabel("<b>Queue Position</b>"),
                 QLabel(str(self.statusData['queue_pos'])))
     body.addRow(QLabel("<b>Active Time</b>"),
                 QLabel(sec_to_time(self.statusData['activetime'])))
     body.addRow(
         QLabel("<b>Last Seen</b>"),
         QLabel(
             time.strftime('%Y-%m-%d %H:%M:%S',
                           time.gmtime(self.statusData['lastseen']))))
     body.addRow(
         QLabel("<b>Last Paid</b>"),
         QLabel(
             time.strftime('%Y-%m-%d %H:%M:%S',
                           time.gmtime(self.statusData['lastpaid']))))
     layout.addLayout(body)
     self.okButton = QPushButton('OK')
     self.okButton.clicked.connect(self.accept)
     layout.addWidget(self.okButton)
     sh = layout.sizeHint()
     self.setFixedSize(sh)
Пример #35
0
	def __init__(self):
		super().__init__()
		self.setWindowTitle("Directory Picker")
		self.url = None

		settings = QFormLayout()

		schemes = QComboBox(self)
		schemes.addItem('')
		schemes.addItem('ftp')
		schemes.addItem('ftps')
		schemes.addItem('gdrive')
		schemes.addItem('http')
		schemes.addItem('https')
		schemes.addItem('sftp')
		settings.addRow(QLabel('Scheme'), schemes)
		self.schemes = schemes

		self.username = Edit(self)
		settings.addRow(QLabel('Username'), self.username)

		self.password = Edit(self)
		settings.addRow(QLabel('Password'), self.password)

		self.host = Edit(self)
		settings.addRow(QLabel('Host'), self.host)

		self.port = Edit(self)
		settings.addRow(QLabel('Port'), self.port)

		self.path = Edit(self)
		settings.addRow(QLabel('Path'), self.path)

		self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
		self.buttonBox.accepted.connect(self.setUrl)
		self.buttonBox.rejected.connect(self.reject)
		self.layout = QVBoxLayout()
		self.layout.addLayout(settings)
		self.layout.addStretch()
		self.layout.addWidget(self.buttonBox)
		self.setLayout(self.layout)
Пример #36
0
    def initUI(self):
        mainLayout=QVBoxLayout()
        layH1=QHBoxLayout()
        layH2=QHBoxLayout()
        self.conflist=QListWidget()
        self.stack=QStackedWidget()
        layH1.addWidget(self.conflist)
        layH1.addWidget(self.stack)
        self.okbtn=QPushButton(self.tr("OK"))
        self.cancelbtn=QPushButton(self.tr("Cancel"))
        layH2.addStretch(1)
        layH2.addWidget(self.okbtn)
        layH2.addWidget(self.cancelbtn)
        mainLayout.addLayout(layH1)
        mainLayout.addLayout(layH2)
        self.setLayout(mainLayout)

        #list
        self.conflist.addItem(self.tr("General"))
        self.conflist.addItem(self.tr("Editor"))
        self.conflist.setMaximumWidth(150)
        #general
        w=QWidget()
        layw=QVBoxLayout()

        g=QGroupBox(self.tr("General"))
        glayout=QFormLayout()
        label1=QLabel(self.tr("select UI language:"))
        self.langCombo=QComboBox()
        self.setLangItems(self.langCombo) #.addItems(self.getLangList())
        self.langCombo.setMinimumWidth(150)
        label2=QLabel(self.tr("Number of recent files:"))
        self.recentcountspin=QSpinBox()
        self.recentcountspin.setMinimum(1)
        self.recentcountspin.setMaximum(30)
        label3 = QLabel(self.tr("Font Size:"))
        self.fontsizespin = QSpinBox()
        self.fontsizespin.setMinimum(1)
        self.fontsizespin.setMaximum(30)

        glayout.addRow(label1,self.langCombo)
        glayout.addRow(label2,self.recentcountspin)
        glayout.addRow(label3,self.fontsizespin)
        g.setLayout(glayout)

        layw.addWidget(g)
        layw.addStretch(1)
        w.setLayout(layw)
        self.stack.addWidget(w)

        #editor
        from ui.editor.settings import EditorSettings
        w=EditorSettings(self.win.editor)
        self.stack.addWidget(w)

        self.conflist.currentRowChanged.connect(self.stack.setCurrentIndex)
        self.cancelbtn.clicked.connect(self.close)
        self.cancelbtn.setVisible(False)
        self.okbtn.clicked.connect(self.close)

        #action
        self.fontsizespin.valueChanged.connect(self.win.editor.font().setPointSize)
        def setCount(x):
            self.win.recent.maxcount=x
        self.recentcountspin.valueChanged.connect(setCount)
        self.langCombo.currentIndexChanged.connect(self.chLang)
Пример #37
0
    def _build_ui(self):
        layout = QGridLayout()
        
        self.alchemy_tabs = QTabWidget()
        
        #substitute
        substitute_tab = QWidget()
        substitute_layout = QGridLayout(substitute_tab) 

        sublabel = QLabel("substituent name:")
        substitute_layout.addWidget(sublabel, 0, 0, Qt.AlignVCenter)
        
        self.subname = QLineEdit()
        # self.subname.setText("Et")
        sub_completer = NameCompleter(Substituent.list(), self.subname)
        self.subname.setCompleter(sub_completer)
        self.subname.setToolTip("name of substituent in the AaronTools library or your personal library\nseparate names with commas and uncheck 'modify selected structure' to create several structures")
        substitute_layout.addWidget(self.subname, 0, 1, Qt.AlignVCenter)
        
        open_sub_lib = QPushButton("from library...")
        open_sub_lib.clicked.connect(self.open_sub_selector)
        substitute_layout.addWidget(open_sub_lib, 0, 2, Qt.AlignTop)        
        
        substitute_layout.addWidget(QLabel("modify selected structure:"), 1, 0, 1, 1, Qt.AlignVCenter)
        
        self.close_previous_sub = QCheckBox()
        self.close_previous_sub.setToolTip("checked: selected structure will be modified\nunchecked: new model will be created for the modified structure")
        self.close_previous_sub.setChecked(self.settings.modify)
        self.close_previous_sub.stateChanged.connect(self.close_previous_change)
        substitute_layout.addWidget(self.close_previous_sub, 1, 1, 1, 2, Qt.AlignTop)    
        
        substitute_layout.addWidget(QLabel("relax substituent:"), 2, 0, 1, 1, Qt.AlignVCenter)
        
        self.minimize = QCheckBox()
        self.minimize.setToolTip("spin the added substituents to try to minimize the LJ potential energy")
        self.minimize.setChecked(self.settings.minimize)
        substitute_layout.addWidget(self.minimize, 2, 1, 1, 1, Qt.AlignTop)
        
        substitute_layout.addWidget(QLabel("guess previous substituent:"), 3, 0, 1, 1, Qt.AlignVCenter)
        
        self.guess_old = QCheckBox()
        self.guess_old.setToolTip("checked: leave the longest connected fragment in the residue\nunchecked: previous substituent must be selected")
        self.guess_old.setChecked(self.settings.guess)
        self.guess_old.stateChanged.connect(lambda state, settings=self.settings: settings.__setattr__("guess", True if state == Qt.Checked else False))
        substitute_layout.addWidget(self.guess_old, 3, 1, 1, 2, Qt.AlignTop)
        
        substitute_layout.addWidget(QLabel("new residue:"), 5, 0, 1, 1, Qt.AlignVCenter)

        self.new_residue = QCheckBox()
        self.new_residue.setToolTip("put the new substituent in its own residue instead\nof adding it to the residue of the old substituent")
        self.new_residue.setChecked(self.settings.new_residue)
        self.new_residue.stateChanged.connect(lambda state, settings=self.settings: settings.__setattr__("new_residue", True if state == Qt.Checked else False))
        substitute_layout.addWidget(self.new_residue, 5, 1, 1, 2, Qt.AlignTop)
        
        substitute_layout.addWidget(QLabel("use distance names:"), 4, 0, 1, 1, Qt.AlignVCenter)
        
        self.use_greek = QCheckBox()
        self.use_greek.setChecked(self.settings.use_greek)
        self.use_greek.setToolTip("indicate distance from point of attachment with atom name")
        substitute_layout.addWidget(self.use_greek, 4, 1, 1, 1, Qt.AlignTop)

        substitute_layout.addWidget(QLabel("change residue name:"), 6, 0, 1, 1, Qt.AlignVCenter)
        
        self.new_sub_name = QLineEdit()
        self.new_sub_name.setToolTip("change name of modified residues")
        self.new_sub_name.setPlaceholderText("leave blank to keep current")
        substitute_layout.addWidget(self.new_sub_name, 6, 1, 1, 2, Qt.AlignTop)

        substitute_button = QPushButton("substitute current selection")
        substitute_button.clicked.connect(self.do_substitute)
        substitute_layout.addWidget(substitute_button, 7, 0, 1, 3, Qt.AlignTop)
        self.substitute_button = substitute_button
        
        substitute_layout.setRowStretch(0, 0)
        substitute_layout.setRowStretch(1, 0)
        substitute_layout.setRowStretch(2, 0)
        substitute_layout.setRowStretch(3, 0)
        substitute_layout.setRowStretch(4, 0)
        substitute_layout.setRowStretch(5, 0)
        substitute_layout.setRowStretch(6, 0)
        substitute_layout.setRowStretch(7, 1)
        
        
        #map ligand
        maplig_tab = QWidget()
        maplig_layout = QGridLayout(maplig_tab)
        
        liglabel = QLabel("ligand name:")
        maplig_layout.addWidget(liglabel, 0, 0, Qt.AlignVCenter)
        
        self.ligname = QLineEdit()
        lig_completer = NameCompleter(Component.list(), self.ligname)
        self.ligname.setCompleter(lig_completer)
        self.ligname.setToolTip("name of ligand in the AaronTools library or your personal library\nseparate names with commas and uncheck 'modify selected structure' to create several structures")
        maplig_layout.addWidget(self.ligname, 0, 1, Qt.AlignVCenter)
        
        open_lig_lib = QPushButton("from library...")
        open_lig_lib.clicked.connect(self.open_lig_selector)
        maplig_layout.addWidget(open_lig_lib, 0, 2, Qt.AlignTop)        
        
        maplig_layout.addWidget(QLabel("modify selected structure:"), 1, 0, 1, 1, Qt.AlignVCenter)
        
        self.close_previous_lig = QCheckBox()
        self.close_previous_lig.setToolTip("checked: selected structure will be modified\nunchecked: new model will be created for the modified structure")
        self.close_previous_lig.setChecked(self.settings.modify)
        self.close_previous_lig.stateChanged.connect(self.close_previous_change)
        maplig_layout.addWidget(self.close_previous_lig, 1, 1, 1, 2, Qt.AlignTop)

        maplig_button = QPushButton("swap ligand with selected coordinating atoms")
        maplig_button.clicked.connect(self.do_maplig)
        maplig_layout.addWidget(maplig_button, 2, 0, 1, 3, Qt.AlignTop)
        self.maplig_button = maplig_button

        start_structure_button = QPushButton("place in:")
        self.lig_model_selector = ModelComboBox(self.session, addNew=True)
        start_structure_button.clicked.connect(self.do_new_lig)
        maplig_layout.addWidget(start_structure_button, 3, 0, 1, 1, Qt.AlignTop)
        maplig_layout.addWidget(self.lig_model_selector, 3, 1, 1, 2, Qt.AlignTop)

        maplig_layout.setRowStretch(0, 0)
        maplig_layout.setRowStretch(1, 0)
        maplig_layout.setRowStretch(2, 0)
        maplig_layout.setRowStretch(3, 1)
        
        
        #close ring
        closering_tab = QWidget()
        closering_layout = QGridLayout(closering_tab)
        
        ringlabel = QLabel("ring name:")
        closering_layout.addWidget(ringlabel, 0, 0, Qt.AlignVCenter)
        
        self.ringname = QLineEdit()
        ring_completer = NameCompleter(Ring.list(), self.ringname)
        self.ringname.setCompleter(ring_completer)
        self.ringname.setToolTip("name of ring in the AaronTools library or your personal library\nseparate names with commas and uncheck 'modify selected structure' to create several structures")
        closering_layout.addWidget(self.ringname, 0, 1, Qt.AlignVCenter)
        
        open_ring_lib = QPushButton("from library...")
        open_ring_lib.clicked.connect(self.open_ring_selector)
        closering_layout.addWidget(open_ring_lib, 0, 2, Qt.AlignTop)        
        
        closering_layout.addWidget(QLabel("modify selected structure:"), 1, 0, 1, 1, Qt.AlignVCenter) 
        
        self.close_previous_ring = QCheckBox()
        self.close_previous_ring.setToolTip("checked: selected structure will be modified\nunchecked: new model will be created for the modified structure")
        self.close_previous_ring.setChecked(self.settings.modify)
        self.close_previous_ring.stateChanged.connect(self.close_previous_change)
        closering_layout.addWidget(self.close_previous_ring, 1, 1, 1, 2, Qt.AlignTop)

        closering_layout.addWidget(QLabel("try multiple:"), 2, 0, 1, 1, Qt.AlignVCenter)

        self.minimize_ring = QCheckBox()
        self.minimize_ring.setToolTip("try to use other versions of this ring in the library to find the one that fits best")
        self.minimize_ring.setChecked(self.settings.minimize_ring)
        closering_layout.addWidget(self.minimize_ring, 2, 1, 1, 2, Qt.AlignTop)

        closering_layout.addWidget(QLabel("new residue name:"), 3, 0, 1, 1, Qt.AlignVCenter)
        
        self.new_ring_name = QLineEdit()
        self.new_ring_name.setToolTip("change name of modified residues")
        self.new_ring_name.setPlaceholderText("leave blank to keep current")
        closering_layout.addWidget(self.new_ring_name, 3, 1, 1, 2, Qt.AlignTop)

        closering_button = QPushButton("put a ring on current selection")
        closering_button.clicked.connect(self.do_fusering)

        closering_layout.addWidget(closering_button, 4, 0, 1, 3, Qt.AlignTop)
        self.closering_button = closering_button

        start_structure_button = QPushButton("place in:")
        self.ring_model_selector = ModelComboBox(self.session, addNew=True)
        start_structure_button.clicked.connect(self.do_new_ring)
        closering_layout.addWidget(start_structure_button, 5, 0, 1, 1, Qt.AlignTop)
        closering_layout.addWidget(self.ring_model_selector, 5, 1, 1, 2, Qt.AlignTop)

        closering_layout.setRowStretch(0, 0)
        closering_layout.setRowStretch(1, 0)
        closering_layout.setRowStretch(2, 0)
        closering_layout.setRowStretch(3, 0)
        closering_layout.setRowStretch(4, 0)
        closering_layout.setRowStretch(5, 1)


        #change element
        changeelement_tab = QWidget()
        changeelement_layout = QFormLayout(changeelement_tab)
        
        self.element = QPushButton("C")
        self.element.setMinimumWidth(int(1.3*self.element.fontMetrics().boundingRect("QQ").width()))
        self.element.setMaximumWidth(int(1.3*self.element.fontMetrics().boundingRect("QQ").width()))
        self.element.setMinimumHeight(int(1.5*self.element.fontMetrics().boundingRect("QQ").height()))
        self.element.setMaximumHeight(int(1.5*self.element.fontMetrics().boundingRect("QQ").height()))
        ele_color = tuple(list(element_color(ELEMENTS.index("C")))[:-1])
        self.element.setStyleSheet(
            "QPushButton { background: rgb(%i, %i, %i); color: %s; font-weight: bold; }" % (
                *ele_color,
                'white' if sum(
                    int(x < 130) - int(x > 225) for x in ele_color
                ) - int(ele_color[1] > 225) +
                int(ele_color[2] > 200) >= 2 else 'black'
            )
        )
        self.element.clicked.connect(self.open_ptable)
        changeelement_layout.addRow("element:", self.element)
        
        self.vsepr = QComboBox()
        self.vsepr.addItems([
            "do not change",                  # 0
            
            "linear (1 bond)",                # 1
            
            "linear (2 bonds)",               # 2 
            "trigonal planar (2 bonds)",      # 3
            "tetrahedral (2 bonds)",          # 4 
            
            "trigonal planar",                # 5
            "tetrahedral (3 bonds)",          # 6
            "T-shaped",                       # 7
            
            "trigonal pyramidal",             # 8
            "tetrahedral",                    # 9
            "sawhorse",                       #10
            "seesaw",                         #11
            "square planar",                  #12
            
            "trigonal bipyramidal",           #13
            "square pyramidal",               #14
            "pentagonal",                     #15
            
            "octahedral",                     #16
            "hexagonal",                      #17
            "trigonal prismatic",             #18
            "pentagonal pyramidal",           #19
            
            "capped octahedral",              #20
            "capped trigonal prismatic",      #21
            "heptagonal",                     #22
            "hexagonal pyramidal",            #23
            "pentagonal bipyramidal",         #24
            
            "biaugmented trigonal prismatic", #25
            "cubic",                          #26
            "elongated trigonal bipyramidal", #27
            "hexagonal bipyramidal",          #28
            "heptagonal pyramidal",           #29
            "octagonal",                      #30
            "square antiprismatic",           #31
            "trigonal dodecahedral",          #32
            
            "capped cube",                    #33
            "capped square antiprismatic",    #34
            "enneagonal",                     #35
            "heptagonal bipyramidal",         #36
            "hula-hoop",                      #37
            "triangular cupola",              #38
            "tridiminished icosahedral",      #39
            "muffin",                         #40
            "octagonal pyramidal",            #41
            "tricapped trigonal prismatic",   #42
        ])
        
        self.vsepr.setCurrentIndex(9)
        
        self.vsepr.insertSeparator(33)
        self.vsepr.insertSeparator(25)
        self.vsepr.insertSeparator(20)
        self.vsepr.insertSeparator(16)
        self.vsepr.insertSeparator(13)
        self.vsepr.insertSeparator(8)
        self.vsepr.insertSeparator(5)
        self.vsepr.insertSeparator(2)
        self.vsepr.insertSeparator(1)
        self.vsepr.insertSeparator(0)
        changeelement_layout.addRow("geometry:", self.vsepr)
        
        self.change_bonds = QCheckBox()
        self.change_bonds.setChecked(self.settings.change_bonds)
        changeelement_layout.addRow("adjust bond lengths:", self.change_bonds)
        
        change_element_button = QPushButton("change selected elements")
        change_element_button.clicked.connect(self.do_change_element)
        changeelement_layout.addRow(change_element_button)
        self.change_element_button = change_element_button

        start_structure_button = QPushButton("place in:")
        self.model_selector = ModelComboBox(self.session, addNew=True)
        start_structure_button.clicked.connect(self.do_new_atom)
        changeelement_layout.addRow(start_structure_button, self.model_selector)
        
        delete_atoms_button = QPushButton("delete selected atoms")
        delete_atoms_button.clicked.connect(self.delete_atoms)
        changeelement_layout.addRow(delete_atoms_button)

        self.alchemy_tabs.addTab(substitute_tab, "substitute")
        self.alchemy_tabs.addTab(maplig_tab, "swap ligand")
        self.alchemy_tabs.addTab(closering_tab, "fuse ring")
        self.alchemy_tabs.addTab(changeelement_tab, "change element")

        layout.addWidget(self.alchemy_tabs)

        self.tool_window.ui_area.setLayout(layout)

        self.tool_window.manage(None)
    def init_line_edit(self):
        fbox = QFormLayout()
        self.setLayout(fbox)
        label_sf = QLabel('SimpleForm')
        label_sf.setStyleSheet("color: blue; font: bold 20px")

        vbox = QVBoxLayout()
        fbox.addRow(None, label_sf)

        label_name = QLabel('Name')
        fbox.addRow(label_name, vbox)

        edit_name = QLineEdit()
        edit_name.setMinimumWidth(300)
        fbox.addRow(label_name, edit_name)

        hbox = QHBoxLayout()
        radio_male = QRadioButton("Male")
        radio_female = QRadioButton("Female")
        hbox.addWidget(radio_male)
        hbox.addWidget(radio_female)
        hbox.addStretch()
        fbox.addRow(QLabel("Gender"), hbox)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(QPushButton("Submit"))
        hbox.addWidget(QPushButton("Cancel"))
        fbox.addRow(hbox)
Пример #39
0
class PropertiesWidget(QWidget):
    """
    A widget for displaying & editing properties of objects etc.

    Also see the properties this likes to display:
    also see: supertux/property.py
    """

    def __init__(self, parent):
        super().__init__(parent)
        self.items = []

        self.vbox = QVBoxLayout()
        self.layout = QFormLayout()
        self.vbox.addLayout(self.layout)

        self.setLayout(self.vbox)
        self.setMinimumWidth(300)

        # Called in many cases. This should have functions connected
        # which cause the changes in the widget to be applied
        # Called by hitting "Apply", "Ok" or "Finish"
        self.call_signal = Signal()

        self.call_signal.connect(self.call_callbacks)

    def clear_properties(self):
        # Clear Items
        self.items = []
        # Remove all widgets
        for i in range(self.layout.count()):
            self.layout.layout().takeAt(0).widget().setParent(None)

    def set_properties(self, props):
        # Clear previous properties
        self.clear_properties()

        # Add all properties
        for prop in props:
            prop.property_dialog(self)

    def add_label(self, text):
        label = QLabel(text)
        self.layout.addRow(label)
        self.items.append(Item(Item.KIND_LABEL, label, None, None))

    def add_bool(self, name, value, callback):
        label = QLabel(name)
        checkbox = QCheckBox()
        self.layout.addRow(label, checkbox)

        if value:
            checkbox.setCheckState(Qt.Checked)

        self.items.append(Item(Item.KIND_BOOL, label, checkbox, callback=callback))

    def add_int(self, name, value, callback=None):
        label = QLabel(name)
        inputbox = QSpinBox()
        self.layout.addRow(label, inputbox)

        inputbox.setValue(value)

        self.items.append(Item(Item.KIND_INT, label, inputbox, callback=callback))

    def add_float(self, name, value, callback=None):
        label = QLabel(name)
        inputbox = QLineEdit()
        self.layout.addRow(label, inputbox)
        inputbox.setText(str(value))

        self.items.append(Item(Item.KIND_FLOAT, label, inputbox, callback=callback))

    def add_string(self, name, value, callback=None, placeholder=None):
        label = QLabel(name)
        inputbox = QLineEdit()
        self.layout.addRow(label, inputbox)

        inputbox.setText(value)
        if placeholder is not None:
            inputbox.setPlaceholderText(placeholder)

        self.items.append(Item(Item.KIND_STRING, label, inputbox, callback=callback))

    def add_file(self, label, default, ret_rel_to=None, show_rel_to=None, open_in=None, filters=("All Files (*)",),
                 callback=None):
        """Open a FileDialog for the user to select a file

        :param ret_rel_to: Path to which the param. of callback(value)
         will be relative to
        :param show_rel_to: Path to which the displayed text (in input box)
         will be relative to
        :param open_in: Where the open file dialog will begin
        :param callback: Method/function to call upon file being chosen.
        :param filters: A tuple containing filters for filenames. They should appear like this:
                        Name of Filter (*.txt)
                        ^ Only show .txt files
                        All Files (*)
                        C++ Files (*.cpp *.h *.hpp *.cxx)
        """
        label = QLabel(label)
        inputbox = QLineEdit(default)
        browse = QPushButton("Browse...")

        def file_selected(path):
            """Called whenever file is selected"""
            # actual_path = path
            if show_rel_to and path[:len(show_rel_to)] == show_rel_to:
                inputbox.setText(path[len(show_rel_to):])
            else:
                inputbox.setText(path)

        def browse_files():
            """Called when Browse... button clicked"""
            dialog = OpenFileDialog("Open File")
            dialog.set_directory(open_in if open_in else Config.current.datadir)
            dialog.run(file_selected)

        browse.clicked.connect(browse_files)  # Connect the above to click signal

        self.layout.addRow(label, inputbox)
        self.layout.addRow(browse)

        self.items.append(Item(Item.KIND_STRING, label, inputbox, callback=callback))

    def add_enum(self, name, values, current_value=0, callback=None):
        label = QLabel(name)
        drop_down = QComboBox()
        for value in values:
            drop_down.addItem(value)
        drop_down.setCurrentIndex(current_value)
        self.layout.addRow(label, drop_down)

        self.items.append(Item(Item.KIND_ENUM, label, drop_down, callback=callback, group=None))

    def add_radio(self, name, values, current_value=0, callback=None):
        label = QLabel(name)
        group = QButtonGroup()
        for i, value in enumerate(values):
            radio = QRadioButton(value)
            radio.setChecked(current_value == i)
            if i == 0:
                self.layout.addRow(label, radio)
            else:
                self.layout.addRow(None, radio)
            group.addButton(radio)

        self.items.append(Item(Item.KIND_ENUM, label, None, callback=callback, group=group))

    def add_color(self, name, color, callback=None):
        """Not fully implemented according to Item class at the top."""
        label = QLabel(name)
        pixmap = QPixmap(32, 32)
        pixmap.fill(color.to_qt())
        icon = QIcon(pixmap)
        colorbutton = QPushButton(icon, color.to_hex())

        def on_color(qcolor):
            pixmap.fill(qcolor)
            icon.addPixmap(pixmap)
            colorbutton.setIcon(icon)
            colorbutton.setText(qcolor.name())

        self.layout.addRow(label, colorbutton)

        self.items.append(Item(Item.KIND_COLOR, label, colorbutton, callback=callback))

    def call_callbacks(self, *args):
        for item in self.items:
            if item.callback is not None:
                item.callback(item.get_value())

    def get_values(self):
        result = []

        for item in self.items:
            value = item.get_value()
            if value is not None:
                result.append(value)

        return result

    def add_callback(self, callback):
        """Adds a callback to the callback signal"""
        self.call_signal.connect(callback)

    def call(self):
        self.call_signal(*self.get_values())
Пример #40
0
 def __init__(self, ebeveyn=None):
     super(PaketBilgiPencere, self).__init__(ebeveyn)
     self.ebeveyn = ebeveyn
     merkez_kutu = QVBoxLayout()
     merkez_kutu.setContentsMargins(10, 10, 10, 10)
     dugmeler_kutu = QHBoxLayout()
     merkez_kutu.addLayout(dugmeler_kutu)
     form_kutu = QFormLayout()
     merkez_kutu.addLayout(form_kutu)
     self.setLayout(merkez_kutu)
     self.icon_label = QLabel()
     dugmeler_kutu.addWidget(self.icon_label)
     self.kur_sil_dugme = QPushButton()
     self.kur_sil_dugme.clicked.connect(self.paket_kur_sil_fonk)
     dugmeler_kutu.addWidget(self.kur_sil_dugme)
     self.kur_sil_dugme.setFixedHeight(64)
     self.geri_dugme = QPushButton("Geri")
     self.geri_dugme.setStyleSheet(
         "background-color:#3689e6;border:None;color:#ffffff;font-weight:bold"
     )
     self.geri_dugme.setIcon(QIcon("./iconlar/geri.svg"))
     self.geri_dugme.setIconSize(QSize(48, 48))
     self.geri_dugme.clicked.connect(self.geri_fonk)
     dugmeler_kutu.addWidget(self.geri_dugme)
     self.geri_dugme.setFixedHeight(64)
     self.adi_label = QLabel()
     form_kutu.addRow(QLabel("<b>Adı\t: </b>"), self.adi_label)
     self.tanim_label = QLabel()
     self.tanim_label.setWordWrap(True)
     form_kutu.addRow(QLabel("<b>Tanımı\t: </b>"), self.tanim_label)
     self.url_label = QLabel()
     form_kutu.addRow(QLabel("<b>Url\t: </b>"), self.url_label)
     self.paketci_label = QLabel()
     form_kutu.addRow(QLabel("<b>Paketçi\t: </b>"), self.paketci_label)
     self.surum_label = QLabel()
     form_kutu.addRow(QLabel("<b>Sürüm\t: </b>"), self.surum_label)
     self.devir_label = QLabel()
     form_kutu.addRow(
         QLabel("<b>Devir\t: </b>"),
         self.devir_label,
     )
     self.grup_label = QLabel()
     form_kutu.addRow(QLabel("<b>Grup\t: </b>"), self.grup_label)
     self.gerekler_label = QLabel()
     self.gerekler_label.setWordWrap(True)
     form_kutu.addRow(QLabel("<b>Gerekler\t: </b>"), self.gerekler_label)
     self.kaynak_1_label = QLabel()
     self.kaynak_1_label.setTextInteractionFlags(Qt.TextBrowserInteraction)
     self.kaynak_1_label.linkActivated.connect(self.kaynak_tiklandi)
     form_kutu.addRow(QLabel("<b>Kaynak-1\t: </b>"), self.kaynak_1_label)
Пример #41
0
    def __init__(self, parent=None, **kwargs):
        BaseEditorOrange.__init__(self, parent, **kwargs)

        self.scaling = True  # FIXME: for the reference display to work. Why?

        self.controlArea.setLayout(QVBoxLayout())

        self.reference = None
        self.preview_data = None

        self.max_iter = self.MAX_ITER_DEFAULT
        self.fixed_iter = self.FIXED_ITER_DEFAULT
        self.ncomp = self.NCOMP_DEFAULT
        self.autoset_ncomp = self.AUTOSET_NCOMP_DEFAULT
        self.n0_low = self.N0_LOW
        self.n0_high = self.N0_HIGH
        self.a_low = self.A_LOW
        self.a_high = self.A_HIGH

        gui.spin(self.controlArea, self, "max_iter", label="Max iterations", minv=0, maxv=100,
                 controlWidth=50, callback=self.edited.emit)
        gui.checkBox(self.controlArea, self, "fixed_iter", label="Always perform max iterations",
                     callback=self.edited.emit)

        self.comp_spin = gui.spin(self.controlArea, self, "ncomp", label="Components",
                                  minv=3, maxv=15,
                                  controlWidth=50, callback=self.edited.emit)
        gui.checkBox(self.controlArea, self, "autoset_ncomp",
                     label="Automatically set components",
                     callback=lambda: (self._auto_click(), self.edited.emit()))

        form_set = QFormLayout()
        self.controlArea.layout().addLayout(form_set)

        bint = QBoxLayout(0)
        low = lineEditFloatRange(self, self, "n0_low", bottom=1.1, top=3,
                                 callback=self.edited.emit)
        low.sizeHintFactor = 0.4
        bint.addWidget(low)
        high = lineEditFloatRange(self, self, "n0_high", bottom=1.1, top=3,
                                 callback=self.edited.emit)
        high.sizeHintFactor = 0.4
        bint.addWidget(high)
        form_set.addRow("Refractive index", bint)

        bint = QBoxLayout(0)
        low = lineEditFloatRange(self, self, "a_low", bottom=2, top=50,
                                 callback=self.edited.emit)
        low.sizeHintFactor = 0.4
        bint.addWidget(low)
        high = lineEditFloatRange(self, self, "a_high", bottom=2, top=50,
                                 callback=self.edited.emit)
        high.sizeHintFactor = 0.4
        bint.addWidget(high)
        form_set.addRow("Spherical radius", bint)

        self.reference_info = QLabel("", self)
        self.controlArea.layout().addWidget(self.reference_info)

        self.output_model = self.OUTPUT_MODEL_DEFAULT
        gui.checkBox(self.controlArea, self, "output_model", "Output EMSC model",
                     callback=self.edited.emit)

        self._auto_click()
        self._init_regions()
        self._init_reference_curve()

        self.user_changed = False
Пример #42
0
	def __init__(self):

		

		self.player_class = "No Class"
		self.player_name = "Zorg"
		self.character_name = "Character"

		self.barbarianString = "Barbarian"
		self.noClassString = "No Class"
		self.knightString = "Knight"
		self.nerdString = "Nerd"
		self.rogueString = "Rogue"


		super().__init__()


		######################################################################################################
		# Creating Layouts
		######################################################################################################

		# Sets as child to CentralWidget
		self.mainLayout = QVBoxLayout(self)

		self.interactionLayout = QVBoxLayout()

		self.attributeInventoryLayout = QHBoxLayout()

		self.imageInventoryLayout = QVBoxLayout()

		self.attributesLayout = QVBoxLayout()

		# Form layout for class and difficulty setters
		self.informationFormLayout = QFormLayout()
		self.informationFormLayout.setVerticalSpacing(25)


		######################################################################################################
		# Creating widgets to go in layouts
		######################################################################################################

		# Used to enter the player's name
		self.playerNameLineEdit = QLineEdit()
		self.playerNameLineEdit.setPlaceholderText("Enter player name here ")

		# Used to enter the character's name
		self.characterNameLineEdit = QLineEdit()
		self.characterNameLineEdit.setPlaceholderText("Enter character name here ")

		# Changes the below labels
		self.classSelectorComboBox = QComboBox()
		self.classSelectorComboBox.addItems([self.noClassString,self.barbarianString, self.knightString, self.nerdString, self.rogueString])

		# TBD add difficulty to game
		self.difficultyComboBox = QComboBox()
		self.difficultyComboBox.addItems(["Newb", "Decent", "Gud"])

		# Used to start the game
		self.finishPushButton = QPushButton("Finish")


		# Labels to display information to the user
		self.difficultyLabel = QLabel("A good difficulty for children and casuals")

		self.strengthLabel = QLabel("Strength: 10")

		self.dexterityLabel = QLabel("Dexterity: 10")

		self.constitutionLabel = QLabel("Constitution: 10")

		self.intellectLabel = QLabel("Intellect: 10")

		self.smallImageLabel = QLabel()

		self.inventoryLabel = QLabel("No class starts with a fist")



		######################################################################################################
		# Changing the looks of the widgets
		######################################################################################################

		self.imageResourceString = "resources/questionbox.jpg"
		self.smallImage = QImage(self.imageResourceString)
		self.smallerImage= self.smallImage.scaled(50,50)

		self.smallImagePixmap = QPixmap(self.smallerImage)

		self.smallImageLabel.setPixmap(self.smallImagePixmap)


		# Center imageInventory layout
		self.imageInventoryLayout.setAlignment(Qt.AlignCenter)

		## Center the image left to right in the layout
		self.smallImageLabel.setAlignment(Qt.AlignCenter)


		## Changing the colors of finishPushButton, difficultyComboBox, classSelectorComboBox
		newPalettePushButton = self.finishPushButton.palette()
		newPalettePushButton.setColor(newPalettePushButton.Button, QColor(255, 0, 0))
		self.finishPushButton.setAutoFillBackground( True )
		self.finishPushButton.setPalette(newPalettePushButton)

		newPaletteDifficultyComboBox = self.difficultyComboBox.palette()
		newPaletteDifficultyComboBox.setColor(self.difficultyComboBox.backgroundRole(), QColor(123, 123, 123))
		self.difficultyComboBox.setAutoFillBackground( True )
		self.difficultyComboBox.setPalette(newPaletteDifficultyComboBox)






		######################################################################################################
		# re-Parenting mainLayout
		######################################################################################################

		# The order widgets are added change the order they appear in the layout
		# Since main is QV order determines top to bottom
		self.mainLayout.addLayout(self.interactionLayout)

		self.mainLayout.addLayout(self.attributeInventoryLayout)

		self.mainLayout.addWidget(self.finishPushButton)


		######################################################################################################
		# re-Parenting interactionLayout
		######################################################################################################

		self.interactionLayout.addLayout(self.informationFormLayout)

		self.interactionLayout.addWidget(self.difficultyLabel)


		######################################################################################################
		# re-Parenting attributeInventoryLayout
		######################################################################################################

		self.attributeInventoryLayout.addLayout(self.attributesLayout)

		self.attributeInventoryLayout.addLayout(self.imageInventoryLayout)


		######################################################################################################
		# re-Parenting attributesLayout
		######################################################################################################

		self.attributesLayout.addWidget(self.strengthLabel)

		self.attributesLayout.addWidget(self.dexterityLabel)

		self.attributesLayout.addWidget(self.constitutionLabel)

		self.attributesLayout.addWidget(self.intellectLabel)

		######################################################################################################
		# re-Parenting imageInventoryLayout
		######################################################################################################

		self.imageInventoryLayout.addWidget(self.smallImageLabel)

		self.imageInventoryLayout.addWidget(self.inventoryLabel)


		######################################################################################################
		# Creating form layout for informationFormLayout
		######################################################################################################

		self.informationFormLayout.addRow("Player Name: ", self.playerNameLineEdit)

		self.informationFormLayout.addRow("Character Name: ", self.characterNameLineEdit)

		self.informationFormLayout.addRow("Class: ", self.classSelectorComboBox)

		self.informationFormLayout.addRow("Difficulty: ", self.difficultyComboBox)


		######################################################################################################
		# Connecting the widgets with methods
		######################################################################################################

		self.playerNameLineEdit.textChanged.connect(self.playerNameChange)

		self.classSelectorComboBox.activated[str].connect(self.classChange)

		self.classSelectorComboBox.activated[str].connect(self.classImageChange)

		self.difficultyComboBox.activated[str].connect(self.difficultyChange)

		self.finishPushButton.clicked.connect(self.finishChange)
Пример #43
0
 def __generateLayout__(self):
     layout = QFormLayout()
     layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
     layout.setContentsMargins(10, 5, 10, 5)
     layout.setVerticalSpacing(5)
     layout.setLabelAlignment(Qt.AlignLeft)
     layout.setFormAlignment(Qt.AlignLeft | Qt.AlignTop)
     return layout
Пример #44
0
class CharacterCreateWidget(QWidget):
	"""
	Making a class from the QWidget class, is used in the game to receive information
	 from the user to be used for the character's information.

	Variables:
		mainLayout <QVBoxLayout>
		interactionLayout <QVBoxLayout>
		attributeInventoryLayout <QHBoxLayout>
		attributeLayout <QVBoxLayout>
		informationFormLayout<QFormLayout>

		characterNameLineEdit <QLineEdit>
		playerNameLineEdit <QLineEdit>
		classSelectorComboBox <QComboBox>
		difficultyComboBox <QComboBox>
		finishPushButton <QPushButton>

		difficultyLabel <QLabel>
		strengthLabel <QLabel>
		dexterifyLabel <QLabel>
		constitutionLabel <QLabel>
		intellectLabel <QLabel>
		smallImageLabel <QLabel>
		inventoryLabel <QLabel>

		

		player_class <str>
		player_name <str>
		character_name <str>
		barbarianString <str>
		noClassString <str>
		knightString <str>
		nerdString <str>
		rogueString <str>
		imageResourceString <str>

	Methods:
		classChange Changes text labels related to class
		classImageChange Changes image related to class
		difficultyChange Changes difficulty label
		finishChange Emits signals to centralwidget with the information provided by this screen
		playerNameChange Changes player_name variables 
		
	"""
	procGameStart = pyqtSignal(int, str, str, str)
	procCharLabel = pyqtSignal(str)

	def __init__(self):

		

		self.player_class = "No Class"
		self.player_name = "Zorg"
		self.character_name = "Character"

		self.barbarianString = "Barbarian"
		self.noClassString = "No Class"
		self.knightString = "Knight"
		self.nerdString = "Nerd"
		self.rogueString = "Rogue"


		super().__init__()


		######################################################################################################
		# Creating Layouts
		######################################################################################################

		# Sets as child to CentralWidget
		self.mainLayout = QVBoxLayout(self)

		self.interactionLayout = QVBoxLayout()

		self.attributeInventoryLayout = QHBoxLayout()

		self.imageInventoryLayout = QVBoxLayout()

		self.attributesLayout = QVBoxLayout()

		# Form layout for class and difficulty setters
		self.informationFormLayout = QFormLayout()
		self.informationFormLayout.setVerticalSpacing(25)


		######################################################################################################
		# Creating widgets to go in layouts
		######################################################################################################

		# Used to enter the player's name
		self.playerNameLineEdit = QLineEdit()
		self.playerNameLineEdit.setPlaceholderText("Enter player name here ")

		# Used to enter the character's name
		self.characterNameLineEdit = QLineEdit()
		self.characterNameLineEdit.setPlaceholderText("Enter character name here ")

		# Changes the below labels
		self.classSelectorComboBox = QComboBox()
		self.classSelectorComboBox.addItems([self.noClassString,self.barbarianString, self.knightString, self.nerdString, self.rogueString])

		# TBD add difficulty to game
		self.difficultyComboBox = QComboBox()
		self.difficultyComboBox.addItems(["Newb", "Decent", "Gud"])

		# Used to start the game
		self.finishPushButton = QPushButton("Finish")


		# Labels to display information to the user
		self.difficultyLabel = QLabel("A good difficulty for children and casuals")

		self.strengthLabel = QLabel("Strength: 10")

		self.dexterityLabel = QLabel("Dexterity: 10")

		self.constitutionLabel = QLabel("Constitution: 10")

		self.intellectLabel = QLabel("Intellect: 10")

		self.smallImageLabel = QLabel()

		self.inventoryLabel = QLabel("No class starts with a fist")



		######################################################################################################
		# Changing the looks of the widgets
		######################################################################################################

		self.imageResourceString = "resources/questionbox.jpg"
		self.smallImage = QImage(self.imageResourceString)
		self.smallerImage= self.smallImage.scaled(50,50)

		self.smallImagePixmap = QPixmap(self.smallerImage)

		self.smallImageLabel.setPixmap(self.smallImagePixmap)


		# Center imageInventory layout
		self.imageInventoryLayout.setAlignment(Qt.AlignCenter)

		## Center the image left to right in the layout
		self.smallImageLabel.setAlignment(Qt.AlignCenter)


		## Changing the colors of finishPushButton, difficultyComboBox, classSelectorComboBox
		newPalettePushButton = self.finishPushButton.palette()
		newPalettePushButton.setColor(newPalettePushButton.Button, QColor(255, 0, 0))
		self.finishPushButton.setAutoFillBackground( True )
		self.finishPushButton.setPalette(newPalettePushButton)

		newPaletteDifficultyComboBox = self.difficultyComboBox.palette()
		newPaletteDifficultyComboBox.setColor(self.difficultyComboBox.backgroundRole(), QColor(123, 123, 123))
		self.difficultyComboBox.setAutoFillBackground( True )
		self.difficultyComboBox.setPalette(newPaletteDifficultyComboBox)






		######################################################################################################
		# re-Parenting mainLayout
		######################################################################################################

		# The order widgets are added change the order they appear in the layout
		# Since main is QV order determines top to bottom
		self.mainLayout.addLayout(self.interactionLayout)

		self.mainLayout.addLayout(self.attributeInventoryLayout)

		self.mainLayout.addWidget(self.finishPushButton)


		######################################################################################################
		# re-Parenting interactionLayout
		######################################################################################################

		self.interactionLayout.addLayout(self.informationFormLayout)

		self.interactionLayout.addWidget(self.difficultyLabel)


		######################################################################################################
		# re-Parenting attributeInventoryLayout
		######################################################################################################

		self.attributeInventoryLayout.addLayout(self.attributesLayout)

		self.attributeInventoryLayout.addLayout(self.imageInventoryLayout)


		######################################################################################################
		# re-Parenting attributesLayout
		######################################################################################################

		self.attributesLayout.addWidget(self.strengthLabel)

		self.attributesLayout.addWidget(self.dexterityLabel)

		self.attributesLayout.addWidget(self.constitutionLabel)

		self.attributesLayout.addWidget(self.intellectLabel)

		######################################################################################################
		# re-Parenting imageInventoryLayout
		######################################################################################################

		self.imageInventoryLayout.addWidget(self.smallImageLabel)

		self.imageInventoryLayout.addWidget(self.inventoryLabel)


		######################################################################################################
		# Creating form layout for informationFormLayout
		######################################################################################################

		self.informationFormLayout.addRow("Player Name: ", self.playerNameLineEdit)

		self.informationFormLayout.addRow("Character Name: ", self.characterNameLineEdit)

		self.informationFormLayout.addRow("Class: ", self.classSelectorComboBox)

		self.informationFormLayout.addRow("Difficulty: ", self.difficultyComboBox)


		######################################################################################################
		# Connecting the widgets with methods
		######################################################################################################

		self.playerNameLineEdit.textChanged.connect(self.playerNameChange)

		self.classSelectorComboBox.activated[str].connect(self.classChange)

		self.classSelectorComboBox.activated[str].connect(self.classImageChange)

		self.difficultyComboBox.activated[str].connect(self.difficultyChange)

		self.finishPushButton.clicked.connect(self.finishChange)


	######################################################################################################
	# On Click Methods
	######################################################################################################



	def classChange(self, classNameText):
		"""
		Edits labels based on classNameText value
		## Create a stack layout and have each class have a VBoxLayout and when the signal is sent I change the image that is on top

		Input:
			classNameText <str>

		Output: 
			Change labels
		"""
		self.strengthString = "Strength: 10"
		self.dexterityString = "Dexterity: 10"
		self.constitutionString = "Constitution: 10"
		self.intellectString = "Intellect: 10"
		self.inventoryString = "No class starts with a fist"

		if (classNameText == self.barbarianString):

			self.strengthString ="Strength: 14"

			self.dexterityString = "Dexterity: 8"

			self.constitutionString = "Constitution: 12"

			self.intellectString = "Intellect: 6"

			self.inventoryString = "Barbarians start with an axe"



		elif (classNameText == self.knightString):

			self.strengthString = "Strength: 12"

			self.dexterityString = "Dexterity: 8"

			self.constitutionString = "Constitution: 12"

			self.intellectString = "Intellect: 8"

			self.inventoryString = "Knight = Sword, Duh"

		elif (classNameText == self.nerdString):

			self.strengthString = "Strength: 8"

			self.dexterityString = "Dexterity: 8"

			self.constitutionString = "Constitution: 8"

			self.intellectString = "Intellect: 16"

			self.inventoryString = "Nerds have no weapons"

		elif (classNameText == self.rogueString):

			self.strengthString = "Strength: 6"

			self.dexterityString = "Dexterity: 14"

			self.constitutionString = "Constitution: 8"

			self.intellectString = "Intellect: 12"

			self.inventoryString = "Rogues get a dagger"

		
		self.player_class = classNameText

		self.strengthLabel.setText(self.strengthString)

		self.dexterityLabel.setText(self.dexterityString)

		self.constitutionLabel.setText(self.constitutionString)

		self.intellectLabel.setText(self.intellectString)

		self.inventoryLabel.setText(self.inventoryString)




	def classImageChange(self, classNameText):
		"""
		Edits labels based on classNameText value

		Input:
			classNameText <str>

		Output: None
		"""
		

		if (classNameText == self.barbarianString):

			# ~/Documents/py/graphics_Basics/character_select/resources/
			self.imageResourceString = "resources/barbarian.jpg"
			

		elif (classNameText == self.knightString):

			# ~/Documents/py/graphics_Basics/character_select/resources/
			self.imageResourceString = "resources/knight.jpg"
			

		elif (classNameText == self.nerdString):

			# ~/Documents/py/graphics_Basics/character_select/resources/
			self.imageResourceString = "resources/questionbox.jpg"
			

		elif (classNameText == self.rogueString):

			# ~/Documents/py/graphics_Basics/character_select/resources/
			self.imageResourceString = "resources/rogue.png"
			

		elif (classNameText == self.noClassString):

			# ~/Documents/py/graphics_Basics/character_select/resources/
			self.imageResourceString = "resources/questionbox.jpg"
			

		self.smallImage = QImage(self.imageResourceString)
		self.smallerImage= self.smallImage.scaled(50,50)

		self.smallImagePixmap = QPixmap(self.smallerImage)

		self.smallImageLabel.setPixmap(self.smallImagePixmap)



	def difficultyChange(self, difficultyText):
		"""
		Edits labels based on difficultyText value

		Input:
			difficultyText <str>

		Output: None
		"""

		if (difficultyText == "Newb"):

			self.difficultyLabel.setText("A good difficulty for children and casuals")

		elif (difficultyText == "Decent"):

			self.difficultyLabel.setText("Fun and exciting adventure awaits")


		elif (difficultyText == "Gud"):

			self.difficultyLabel.setText("Good luck")



	def finishChange(self):
		"""
		TBD sends information decided on in the screen to game state
		Currently exits

		Input: None
			
		Output: None
		"""
		
		self.procGameStart.emit(1, self.player_class, self.character_name, self.player_name)
		self.procCharLabel.emit(self.imageResourceString)
		




	def playerNameChange(self, nameText):
		"""
		Changes player_name variable

		Input:
			nameText <str>

		Output: None
		"""
		self.player_name = nameText
Пример #45
0
    def __init__(self):
        super().__init__()
        self.setLayout(QVBoxLayout())
        self.setWindowTitle(i18n("Export settings"))
        buttons = QDialogButtonBox(QDialogButtonBox.Ok
                                   | QDialogButtonBox.Cancel)

        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        mainWidget = QTabWidget()
        self.layout().addWidget(mainWidget)
        self.layout().addWidget(buttons)

        # Set basic crop settings
        # Set which layers to remove before export.
        mainExportSettings = QWidget()
        mainExportSettings.setLayout(QVBoxLayout())
        groupExportCrop = QGroupBox(i18n("Crop settings"))
        formCrop = QFormLayout()
        groupExportCrop.setLayout(formCrop)
        self.chk_toOutmostGuides = QCheckBox(i18n("Crop to outmost guides"))
        self.chk_toOutmostGuides.setChecked(True)
        self.chk_toOutmostGuides.setToolTip(
            i18n(
                "This will crop to the outmost guides if possible and otherwise use the underlying crop settings."
            ))
        formCrop.addRow("", self.chk_toOutmostGuides)
        btn_fromSelection = QPushButton(
            i18n("Set margins from active selection"))
        btn_fromSelection.clicked.connect(self.slot_set_margin_from_selection)
        # This doesn't work.
        formCrop.addRow("", btn_fromSelection)
        self.spn_marginLeft = QSpinBox()
        self.spn_marginLeft.setMaximum(99999)
        self.spn_marginLeft.setSuffix(" px")
        formCrop.addRow(i18n("Left:"), self.spn_marginLeft)
        self.spn_marginTop = QSpinBox()
        self.spn_marginTop.setMaximum(99999)
        self.spn_marginTop.setSuffix(" px")
        formCrop.addRow(i18n("Top:"), self.spn_marginTop)
        self.spn_marginRight = QSpinBox()
        self.spn_marginRight.setMaximum(99999)
        self.spn_marginRight.setSuffix(" px")
        formCrop.addRow(i18n("Right:"), self.spn_marginRight)
        self.spn_marginBottom = QSpinBox()
        self.spn_marginBottom.setMaximum(99999)
        self.spn_marginBottom.setSuffix(" px")
        formCrop.addRow(i18n("Bottom:"), self.spn_marginBottom)
        groupExportLayers = QGroupBox(i18n("Layers"))
        formLayers = QFormLayout()
        groupExportLayers.setLayout(formLayers)
        self.cmbLabelsRemove = labelSelector()
        formLayers.addRow(i18n("Label for removal:"), self.cmbLabelsRemove)
        self.ln_text_layer_name = QLineEdit()
        self.ln_text_layer_name.setToolTip(
            i18n(
                "These are keywords that can be used to identify text layers. A layer only needs to contain the keyword to be recognised. Keywords should be comma seperated."
            ))
        self.ln_panel_layer_name = QLineEdit()
        self.ln_panel_layer_name.setToolTip(
            i18n(
                "These are keywords that can be used to identify panel layers. A layer only needs to contain the keyword to be recognised. Keywords should be comma seperated."
            ))
        formLayers.addRow(i18n("Text Layer Key:"), self.ln_text_layer_name)
        formLayers.addRow(i18n("Panel Layer Key:"), self.ln_panel_layer_name)

        mainExportSettings.layout().addWidget(groupExportCrop)
        mainExportSettings.layout().addWidget(groupExportLayers)
        mainWidget.addTab(mainExportSettings, i18n("General"))

        # CBZ, crop, resize, which metadata to add.
        CBZexportSettings = QWidget()
        CBZexportSettings.setLayout(QVBoxLayout())
        self.CBZactive = QCheckBox(i18n("Export to CBZ"))
        CBZexportSettings.layout().addWidget(self.CBZactive)
        self.CBZgroupResize = comic_export_resize_widget("CBZ")
        CBZexportSettings.layout().addWidget(self.CBZgroupResize)
        self.CBZactive.clicked.connect(self.CBZgroupResize.setEnabled)
        CBZgroupMeta = QGroupBox(i18n("Metadata to add"))
        # CBZexportSettings.layout().addWidget(CBZgroupMeta)
        CBZgroupMeta.setLayout(QFormLayout())

        mainWidget.addTab(CBZexportSettings, "CBZ")

        # ACBF, crop, resize, creator name, version history, panel layer, text layers.
        ACBFExportSettings = QWidget()
        ACBFform = QFormLayout()
        ACBFExportSettings.setLayout(QVBoxLayout())
        ACBFdocInfo = QGroupBox()
        ACBFdocInfo.setTitle(i18n("ACBF Document Info"))
        ACBFdocInfo.setLayout(ACBFform)
        self.lnACBFSource = QLineEdit()
        self.lnACBFSource.setToolTip(
            i18n(
                "Whether the acbf file is an adaption of an existing source, and if so, how to find information about that source. So for example, for an adapted webcomic, the official website url should go here."
            ))
        self.lnACBFID = QLabel()
        self.lnACBFID.setToolTip(
            i18n(
                "By default this will be filled with a generated universal unique identifier. The ID by itself is merely so that comic book library management programs can figure out if this particular comic is already in their database and whether it has been rated. Of course, the UUID can be changed into something else by manually changing the json, but this is advanced usage."
            ))
        self.spnACBFVersion = QSpinBox()
        self.ACBFhistoryModel = QStandardItemModel()
        acbfHistoryList = QListView()
        acbfHistoryList.setModel(self.ACBFhistoryModel)
        btn_add_history = QPushButton(i18n("Add history entry"))
        btn_add_history.clicked.connect(self.slot_add_history_item)
        self.chkIncludeTranslatorComments = QCheckBox()
        self.chkIncludeTranslatorComments.setText(
            i18n("Include Translator's Comments"))
        self.chkIncludeTranslatorComments.setToolTip(
            i18n(
                "A PO file can contain translator's comments. If this is checked, the translations comments will be added as references into the ACBF file."
            ))
        self.lnTranslatorHeader = QLineEdit()

        ACBFform.addRow(i18n("Source:"), self.lnACBFSource)
        ACBFform.addRow(i18n("ACBF UID:"), self.lnACBFID)
        ACBFform.addRow(i18n("Version:"), self.spnACBFVersion)
        ACBFform.addRow(i18n("Version History:"), acbfHistoryList)
        ACBFform.addRow("", btn_add_history)
        ACBFform.addRow("", self.chkIncludeTranslatorComments)
        ACBFform.addRow(i18n("Translator Header:"), self.lnTranslatorHeader)

        ACBFAuthorInfo = QWidget()
        acbfAVbox = QVBoxLayout(ACBFAuthorInfo)
        infoLabel = QLabel(
            i18n(
                "The people responsible for the generation of the CBZ/ACBF files."
            ))
        infoLabel.setWordWrap(True)
        ACBFAuthorInfo.layout().addWidget(infoLabel)
        self.ACBFauthorModel = QStandardItemModel(0, 6)
        labels = [
            i18n("Nick Name"),
            i18n("Given Name"),
            i18n("Middle Name"),
            i18n("Family Name"),
            i18n("Email"),
            i18n("Homepage")
        ]
        self.ACBFauthorModel.setHorizontalHeaderLabels(labels)
        self.ACBFauthorTable = QTableView()
        acbfAVbox.addWidget(self.ACBFauthorTable)
        self.ACBFauthorTable.setModel(self.ACBFauthorModel)
        self.ACBFauthorTable.verticalHeader().setDragEnabled(True)
        self.ACBFauthorTable.verticalHeader().setDropIndicatorShown(True)
        self.ACBFauthorTable.verticalHeader().setSectionsMovable(True)
        self.ACBFauthorTable.verticalHeader().sectionMoved.connect(
            self.slot_reset_author_row_visual)
        AuthorButtons = QHBoxLayout()
        btn_add_author = QPushButton(i18n("Add author"))
        btn_add_author.clicked.connect(self.slot_add_author)
        AuthorButtons.addWidget(btn_add_author)
        btn_remove_author = QPushButton(i18n("Remove author"))
        btn_remove_author.clicked.connect(self.slot_remove_author)
        AuthorButtons.addWidget(btn_remove_author)
        acbfAVbox.addLayout(AuthorButtons)

        ACBFStyle = QWidget()
        ACBFStyle.setLayout(QHBoxLayout())
        self.ACBFStylesModel = QStandardItemModel()
        self.ACBFStyleClass = QListView()
        self.ACBFStyleClass.setModel(self.ACBFStylesModel)
        ACBFStyle.layout().addWidget(self.ACBFStyleClass)
        ACBFStyleEdit = QWidget()
        ACBFStyleEditVB = QVBoxLayout(ACBFStyleEdit)
        self.ACBFfontCombo = QFontComboBox()
        self.ACBFdefaultFont = QComboBox()
        self.ACBFdefaultFont.addItems(
            ["sans-serif", "serif", "monospace", "cursive", "fantasy"])
        self.ACBFBold = QCheckBox(i18n("Bold"))
        self.ACBFItal = QCheckBox(i18n("Italic"))
        self.ACBFStyleClass.clicked.connect(self.slot_set_style)
        self.ACBFStyleClass.selectionModel().selectionChanged.connect(
            self.slot_set_style)
        self.ACBFStylesModel.itemChanged.connect(self.slot_set_style)
        self.ACBFfontCombo.currentFontChanged.connect(
            self.slot_font_current_style)
        self.ACBFfontCombo.setEditable(False)
        self.ACBFBold.toggled.connect(self.slot_font_current_style)
        self.ACBFItal.toggled.connect(self.slot_font_current_style)
        colorWidget = QGroupBox(self)
        colorWidget.setTitle(i18n("Text Colors"))
        colorWidget.setLayout(QVBoxLayout())
        self.regularColor = QColorDialog()
        self.invertedColor = QColorDialog()
        self.btn_acbfRegColor = QPushButton(i18n("Regular Text"), self)
        self.btn_acbfRegColor.clicked.connect(self.slot_change_regular_color)
        self.btn_acbfInvColor = QPushButton(i18n("Inverted Text"), self)
        self.btn_acbfInvColor.clicked.connect(self.slot_change_inverted_color)
        colorWidget.layout().addWidget(self.btn_acbfRegColor)
        colorWidget.layout().addWidget(self.btn_acbfInvColor)
        ACBFStyleEditVB.addWidget(colorWidget)
        ACBFStyleEditVB.addWidget(self.ACBFfontCombo)
        ACBFStyleEditVB.addWidget(self.ACBFdefaultFont)
        ACBFStyleEditVB.addWidget(self.ACBFBold)
        ACBFStyleEditVB.addWidget(self.ACBFItal)
        ACBFStyleEditVB.addStretch()
        ACBFStyle.layout().addWidget(ACBFStyleEdit)

        ACBFTabwidget = QTabWidget()
        ACBFTabwidget.addTab(ACBFdocInfo, i18n("Document Info"))
        ACBFTabwidget.addTab(ACBFAuthorInfo, i18n("Author Info"))
        ACBFTabwidget.addTab(ACBFStyle, i18n("Style Sheet"))
        ACBFExportSettings.layout().addWidget(ACBFTabwidget)
        mainWidget.addTab(ACBFExportSettings, i18n("ACBF"))

        # Epub export, crop, resize, other questions.
        EPUBexportSettings = QWidget()
        EPUBexportSettings.setLayout(QVBoxLayout())
        self.EPUBactive = QCheckBox(i18n("Export to EPUB"))
        EPUBexportSettings.layout().addWidget(self.EPUBactive)
        self.EPUBgroupResize = comic_export_resize_widget("EPUB")
        EPUBexportSettings.layout().addWidget(self.EPUBgroupResize)
        self.EPUBactive.clicked.connect(self.EPUBgroupResize.setEnabled)
        mainWidget.addTab(EPUBexportSettings, "EPUB")

        # For Print. Crop, no resize.
        TIFFExportSettings = QWidget()
        TIFFExportSettings.setLayout(QVBoxLayout())
        self.TIFFactive = QCheckBox(i18n("Export to TIFF"))
        TIFFExportSettings.layout().addWidget(self.TIFFactive)
        self.TIFFgroupResize = comic_export_resize_widget("TIFF")
        TIFFExportSettings.layout().addWidget(self.TIFFgroupResize)
        self.TIFFactive.clicked.connect(self.TIFFgroupResize.setEnabled)
        mainWidget.addTab(TIFFExportSettings, "TIFF")
Пример #46
0
    def modify_window(self):
        self.get_user_columns()

        #make decision betwwen the edit mode or create mode onto the modification window
        try:
            if self.sub_widget1:
                print("bug here")
                self.replace_widget(self.sub_widget1)
                self.edit = True
            if self.sub_widget2:
                print("bug there")
                self.replace_widget(self.sub_widget2)
                self.edit = False
                self.create = True
        except AttributeError as e:
            print("cant replace widget tha is not created")

        self.sub_widget3 = QWidget(self)
        Glayout = QGridLayout(self)
        self.add_widget(self.sub_widget3, Glayout)

        #search section in modification window
        LMname = QLabel("Enter name:", self)
        Glayout.addWidget(LMname, 0, 0)
        self.SSname = QLineEdit(self)
        Glayout.addWidget(self.SSname, 0, 1)
        Searchbtn = QPushButton("Search", self)
        Searchbtn.clicked.connect(self.retrive_data)
        Glayout.addWidget(Searchbtn, 0, 2)

        #edit mode in modification window
        if self.edit:
            self.Notice = QLabel("NOTE:", self)
            Glayout.addWidget(self.Notice, 1, 1)

            Lname = QLabel("Name:", self)
            Glayout.addWidget(Lname, 2, 0)
            self.SName = QLineEdit(self)
            Glayout.addWidget(self.SName, 2, 1)

            Lid = QLabel("ID:", self)
            Glayout.addWidget(Lid, 3, 0)
            self.SId = QLineEdit(self)
            Glayout.addWidget(self.SId, 3, 1)

            Lage = QLabel("Age", self)
            Glayout.addWidget(Lage, 4, 0)
            self.SAge = QLineEdit(self)
            Glayout.addWidget(self.SAge, 4, 1)

            Lmajor = QLabel("Major:", self)
            Glayout.addWidget(Lmajor, 5, 0)
            self.SMajor = QLineEdit(self)
            Glayout.addWidget(self.SMajor, 5, 1)
            num = 5
#create mode in modification window
        elif self.create:
            form_layout = QFormLayout(self)
            for key, value in self.tempo_dict.items():
                form_layout.addRow(QLabel(value, self), QLineEdit(self))
            Glayout.addLayout(form_layout, 1, 0, 1, 3)
            num = int(self.col_no.text()) + 1

#modification window buttons
        self.Submitbtn = QPushButton("Submit", self)
        self.Submitbtn.clicked.connect(self.get_new_data)
        Glayout.addWidget(self.Submitbtn, num, 0)
        Deletebtn = QPushButton("Delete", self)
        Deletebtn.clicked.connect(self.delete_all_data)
        Glayout.addWidget(Deletebtn, num, 1)
        Cancelbtn = QPushButton("Cancel", self)
        Cancelbtn.clicked.connect(self.cancel_operation)
        Glayout.addWidget(Cancelbtn, num, 2)
        self.tempo_dict.clear()
Пример #47
0
 def createFormGroupBoxTheory(self, file):
     self.formGroupBoxTheory = QGroupBox("Extend theory xrange of \"%s\"" %
                                         file.file_name_short)
     layout = QFormLayout()
     self.with_extra_x = QCheckBox(self)
     self.with_extra_x.setChecked(file.with_extra_x)
     layout.addRow('Extra theory xrange?', self.with_extra_x)
     self.with_extra_x.toggled.connect(self.activate_th_widgets)
     # Npoints
     self.th_num_pts = QLineEdit(self)
     intvalidator = QIntValidator()
     intvalidator.setBottom(2)
     self.th_num_pts.setValidator(QIntValidator())
     self.th_num_pts.setText('%s' % file.th_num_pts)
     layout.addRow('Num. of extra point', self.th_num_pts)
     # logspace
     self.th_logspace = QCheckBox(self)
     self.th_logspace.setChecked(file.theory_logspace)
     layout.addRow('logspace', self.th_logspace)
     # theory xmin/max
     dvalidator = QDoubleValidator()
     self.th_xmin = QLineEdit(self)
     self.th_xmax = QLineEdit(self)
     self.th_xmin.setValidator(dvalidator)
     self.th_xmax.setValidator(dvalidator)
     self.th_xmin.textEdited.connect(self.update_current_view_xrange)
     self.th_xmax.textEdited.connect(self.update_current_view_xrange)
     self.th_xmin.setText('%s' % file.theory_xmin)
     self.th_xmax.setText('%s' % file.theory_xmax)
     layout.addRow('xmin theory', self.th_xmin)
     layout.addRow('xmax theory', self.th_xmax)
     # current view theory xmin/max
     self.view_xmin = QLabel(self)
     self.view_xmax = QLabel(self)
     layout.addRow('xmin(current view)', self.view_xmin)
     layout.addRow('xmax(current view)', self.view_xmax)
     self.update_current_view_xrange()
     # set layout
     self.formGroupBoxTheory.setLayout(layout)
     self.activate_th_widgets()
Пример #48
0
    def init_ui(self):
        self.setWindowTitle(_('Entry properties'))
        self.setWindowIcon(QIcon(config.ICON))
        self.setSizeGripEnabled(False)
        self.setModal(True)

        self.layout = QFormLayout(self)
        self.label_surname = QLabel(_('Last name'))
        self.item_surname = QLineEdit()
        self.layout.addRow(self.label_surname, self.item_surname)

        self.label_name = QLabel(_('First name'))
        self.item_name = AdvComboBox()
        self.item_name.addItems(get_names())
        self.layout.addRow(self.label_name, self.item_name)

        self.label_group = QLabel(_('Group'))
        self.item_group = AdvComboBox()
        self.item_group.addItems(get_race_groups())
        self.layout.addRow(self.label_group, self.item_group)

        self.label_team = QLabel(_('Team'))
        self.item_team = AdvComboBox()
        self.item_team.addItems(get_race_teams())
        self.layout.addRow(self.label_team, self.item_team)

        use_birthday = Config().configuration.get('use_birthday', False)
        if use_birthday:
            self.label_birthday = QLabel(_('Birthday'))
            self.item_birthday = QDateEdit()
            self.item_birthday.setObjectName('BirthdayDateEdit')
            self.item_birthday.setDate(date.today())
            self.item_birthday.setMaximumDate(date.today())
            self.layout.addRow(self.label_birthday, self.item_birthday)
        else:
            self.label_year = QLabel(_('Year of birth'))
            self.item_year = QSpinBox()
            self.item_year.setObjectName('YearSpinBox')
            self.item_year.setMinimum(0)
            self.item_year.setMaximum(date.today().year)
            self.item_year.editingFinished.connect(self.year_change)
            self.layout.addRow(self.label_year, self.item_year)

        self.label_qual = QLabel(_('Qualification'))
        self.item_qual = AdvComboBox()
        for i in list(Qualification):
            self.item_qual.addItem(i.get_title())
        self.layout.addRow(self.label_qual, self.item_qual)

        self.is_ok['bib'] = True
        self.label_bib = QLabel(_('Bib'))
        self.item_bib = QSpinBox()
        self.item_bib.setMinimum(0)
        self.item_bib.setMaximum(Limit.BIB)
        self.item_bib.valueChanged.connect(self.check_bib)
        self.layout.addRow(self.label_bib, self.item_bib)

        self.label_bib_info = QLabel('')
        self.layout.addRow(QLabel(''), self.label_bib_info)

        self.label_start = QLabel(_('Start time'))
        self.item_start = QTimeEdit()
        self.item_start.setDisplayFormat(self.time_format)
        self.layout.addRow(self.label_start, self.item_start)

        self.label_start_group = QLabel(_('Start group'))
        self.item_start_group = QSpinBox()
        self.item_start_group.setMinimum(0)
        self.item_start_group.setMaximum(99)
        self.layout.addRow(self.label_start_group, self.item_start_group)

        self.is_ok['card'] = True
        self.label_card = QLabel(_('Punch card #'))
        self.item_card = QSpinBox()
        self.item_card.setMinimum(0)
        self.item_card.setMaximum(9999999)
        self.item_card.valueChanged.connect(self.check_card)
        self.layout.addRow(self.label_card, self.item_card)

        self.label_card_info = QLabel('')
        self.layout.addRow(QLabel(''), self.label_card_info)

        self.item_rented = QCheckBox(_('rented card'))
        self.item_paid = QCheckBox(_('is paid'))
        self.item_out_of_competition = QCheckBox(_('out of competition'))
        self.item_personal = QCheckBox(_('personal participation'))
        self.layout.addRow(self.item_rented, self.item_out_of_competition)
        self.layout.addRow(self.item_paid, self.item_personal)

        self.label_comment = QLabel(_('Comment'))
        self.item_comment = QTextEdit()
        self.item_comment.setTabChangesFocus(True)
        self.layout.addRow(self.label_comment, self.item_comment)

        def cancel_changes():
            self.close()

        def apply_changes():
            try:
                self.apply_changes_impl()
            except Exception as e:
                logging.error(str(e))
            self.close()

        button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                      | QDialogButtonBox.Cancel)
        self.button_ok = button_box.button(QDialogButtonBox.Ok)
        self.button_ok.setText(_('OK'))
        self.button_ok.clicked.connect(apply_changes)
        self.button_cancel = button_box.button(QDialogButtonBox.Cancel)
        self.button_cancel.setText(_('Cancel'))
        self.button_cancel.clicked.connect(cancel_changes)
        self.layout.addRow(button_box)

        self.show()
Пример #49
0
    def initUI(self):
        layout=QFormLayout(self)
        layout2=QFormLayout(self)
        layout3=QFormLayout(self)

        groupe1=QGroupBox("Mysql:",self)
        groupe2 = QGroupBox("MongoDB:", self)

        layout.addRow(groupe1)
        layout.addRow(groupe2)

        l_host=QLabel("Host:",groupe1)
        self.e_host=QLineEdit(groupe1)
        self.e_host.setText("localhost")

        l_username=QLabel("Username:"******"Password:"******"DB Name:", groupe1)
        self.e_dbname = QLineEdit(groupe1)

        l_mhost=QLabel("Host:",groupe2)
        self.e_mhost=QLineEdit(groupe2)
        self.e_mhost.setText("localhost")

        l_port=QLabel("Port:",groupe2)
        self.e_port=QLineEdit(groupe2)
        self.e_port.setText("27017")

        btn = QPushButton('Transform', self)
        btn.setStyleSheet('''QPushButton
        {color: #FFF; background-color: gray;height:45px;font-size:18px;border-radius:20px;}
        QPushButton:hover
        {color: #000; background-color: white;}''')

        layout2.addRow(btn)
        groupe1.setLayout(layout2)
        groupe2.setLayout(layout3)

        layout2.addRow(l_host,self.e_host)
        layout2.addRow(l_username,self.e_username)
        layout2.addRow(l_password,self.e_password)
        layout2.addRow(l_dbname,self.e_dbname)

        layout3.addRow(l_mhost,self.e_mhost)
        layout3.addRow(l_port,self.e_port)
        layout.addRow(btn)

        btn.clicked.connect(self.trigger)
        self.setGeometry(400,300,500,300)
        self.setWindowTitle('Mysql To MongoDB')
        self.show()
Пример #50
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.interface_lng_val = parent.interface_lng_val
        self.con = parent.con
        self.full_dir = parent.full_dir
        self.par = parent

        if self.con.open():
            if 'patches' in self.con.tables():
                self.patches_lst = []
                query = QtSql.QSqlQuery('SELECT * FROM patches')
                query.exec_()
                while query.next():
                    rec = query.value('patch_name')
                    self.patches_lst.append(rec)
                # print(patches_lst)

                self.table = QTableWidget(len(self.patches_lst) + 3, 2)
                self.table.setColumnWidth(0, 150)
                self.table.setColumnWidth(1, 460)
                self.table.setFixedSize(674, 480)
                self.table.setHorizontalHeaderLabels(["Параметр", "Значение"])

                # dimensions
                dimensions_lbl = QLabel('dimensions')
                self.d_1 = QLineEdit()
                self.d_1.setFixedSize(40, 25)
                self.d_2 = QLineEdit()
                self.d_2.setFixedSize(40, 25)
                self.d_3 = QLineEdit()
                self.d_3.setFixedSize(40, 25)
                self.d_4 = QLineEdit()
                self.d_4.setFixedSize(40, 25)
                self.d_5 = QLineEdit()
                self.d_5.setFixedSize(40, 25)
                self.d_6 = QLineEdit()
                self.d_6.setFixedSize(40, 25)
                self.d_7 = QLineEdit()
                self.d_7.setFixedSize(40, 25)
                self.dimensions_hbox = QHBoxLayout()
                self.dimensions_hbox.addWidget(self.d_1)
                self.dimensions_hbox.addWidget(self.d_2)
                self.dimensions_hbox.addWidget(self.d_3)
                self.dimensions_hbox.addWidget(self.d_4)
                self.dimensions_hbox.addWidget(self.d_5)
                self.dimensions_hbox.addWidget(self.d_6)
                self.dimensions_hbox.addWidget(self.d_7)
                self.dimensions_w = QWidget()
                self.dimensions_w.setLayout(self.dimensions_hbox)
                self.table.setCellWidget(0, 1, self.dimensions_w)
                self.table.setCellWidget(0, 0, dimensions_lbl)
                self.table.setRowHeight(0, 40)

                # internalField
                internalField_lbl = QLabel('internalField')
                self.internalField = QComboBox()
                self.internalField.setFixedSize(100, 25)
                internalField_list = ["uniform"]
                self.internalField.addItems(internalField_list)
                self.x = QLineEdit()
                self.x.setFixedSize(40, 25)
                #self.y = QLineEdit()
                #self.y.setFixedSize(40, 25)
                #self.z = QLineEdit()
                #self.z.setFixedSize(40, 25)
                self.internalField_hbox = QHBoxLayout()
                self.internalField_hbox.addWidget(self.internalField)
                self.internalField_hbox.addWidget(self.x)
                #self.internalField_hbox.addWidget(self.y)
                #self.internalField_hbox.addWidget(self.z)
                self.internalField_w = QWidget()
                self.internalField_w.setLayout(self.internalField_hbox)
                self.table.setCellWidget(1, 1, self.internalField_w)
                self.table.setCellWidget(1, 0, internalField_lbl)
                self.table.setRowHeight(1, 40)

                # вывод значений параметров
                if 'T' in self.con.tables():
                    query = QtSql.QSqlQuery()
                    query.exec("SELECT * FROM T")
                    if query.isActive():
                        query.first()
                        value_list = []
                        while query.isValid():
                            value_res = query.value('value')
                            value_list.append(value_res)
                            query.next()

                        # dimensions
                        self.d_1.setText(value_list[0].split(' ')[0])
                        self.d_2.setText(value_list[0].split(' ')[1])
                        self.d_3.setText(value_list[0].split(' ')[2])
                        self.d_4.setText(value_list[0].split(' ')[3])
                        self.d_5.setText(value_list[0].split(' ')[4])
                        self.d_6.setText(value_list[0].split(' ')[5])
                        self.d_7.setText(value_list[0].split(' ')[6])

                        # internalField
                        internalField_mas = self.internalField.count()
                        for i in range(internalField_mas):
                            if self.internalField.itemText(
                                    i) == value_list[1].split(', ')[0]:
                                self.internalField.setCurrentIndex(i)

                        self.x.setText(value_list[1].split(', ')[1])
                        #self.y.setText(value_list[1].split(', ')[2])
                        #self.z.setText(value_list[1].split(', ')[3])

                # boundaryField
                boundaryField_lbl = QLabel('boundaryField')
                self.table.setCellWidget(2, 0, boundaryField_lbl)

                # patches
                k = 3
                self.type_list_main = []
                self.main_grid_list = []
                self.traction_list = []
                self.xyz_1_list_main = []
                self.pressure_list = []
                self.koord_list = []
                self.value_list = []
                self.xyz_2_list_main = []
                self.traction_lbl_list = []
                self.pressure_lbl_list = []
                self.value_lbl_list = []
                j = 2
                bvc = 0
                for el_p in self.patches_lst:
                    el_p_lbl = QLabel(el_p)

                    # type
                    self.type_lbl = QLabel('type:')
                    self.type = QComboBox()
                    self.type.setFixedSize(150, 25)
                    self.type_list = [
                        "symmetryPlane", "tractionDisplacement", "empty",
                        "zeroGradient"
                    ]
                    self.type.addItems(self.type_list)
                    self.main_grid = QGridLayout()
                    self.main_grid.addWidget(self.type_lbl,
                                             0,
                                             0,
                                             alignment=QtCore.Qt.AlignLeft)
                    self.main_grid.addWidget(self.type,
                                             0,
                                             1,
                                             alignment=QtCore.Qt.AlignLeft)
                    self.main_grid.setRowStretch(0, 6500)
                    self.table.setRowHeight(k, 40)
                    self.type_list_main.append(self.type)
                    self.main_grid_list.append(self.main_grid)

                    # traction
                    traction_lbl = QLabel('traction:')
                    self.traction_lbl_list.append(traction_lbl)
                    traction = QComboBox()
                    traction_list = ["uniform", "demo"]
                    traction.addItems(traction_list)
                    x_1 = QLineEdit()
                    x_1.setFixedSize(40, 25)
                    y_1 = QLineEdit()
                    y_1.setFixedSize(40, 25)
                    z_1 = QLineEdit()
                    z_1.setFixedSize(40, 25)
                    xyz_1_list = [x_1, y_1, z_1]
                    self.traction_list.append(traction)
                    self.xyz_1_list_main.append(xyz_1_list)

                    # pressure
                    pressure_lbl = QLabel('pressure:')
                    self.pressure_lbl_list.append(pressure_lbl)
                    pressure = QComboBox()
                    pressure_list = ["uniform", "demo"]
                    pressure.addItems(pressure_list)
                    koord = QLineEdit()
                    koord.setFixedSize(40, 25)
                    self.pressure_list.append(pressure)
                    self.koord_list.append(koord)

                    # value
                    value_lbl = QLabel('value:')
                    self.value_lbl_list.append(value_lbl)
                    value = QComboBox()
                    value_list = ["uniform", "demo"]
                    value.addItems(value_list)
                    x_2 = QLineEdit()
                    x_2.setFixedSize(40, 25)
                    y_2 = QLineEdit()
                    y_2.setFixedSize(40, 25)
                    z_2 = QLineEdit()
                    z_2.setFixedSize(40, 25)
                    xyz_2_list = [x_2, y_2, z_2]
                    self.value_list.append(value)
                    self.xyz_2_list_main.append(xyz_2_list)

                    # вывод значений параметров
                    if 'T' in self.con.tables():
                        query = QtSql.QSqlQuery()
                        query.exec("SELECT * FROM T")
                        if query.isActive():
                            query.first()
                            value_list = []
                            while query.isValid():
                                value_res = query.value('value')
                                value_list.append(value_res)
                                query.next()

                            if ',' not in value_list[j]:
                                type_mas = self.main_grid_list[
                                    bvc].itemAtPosition(0, 1).widget().count()
                                for i in range(type_mas):
                                    if self.main_grid_list[bvc].itemAtPosition(
                                            0, 1).widget().itemText(
                                                i) == value_list[j]:
                                        self.main_grid_list[
                                            bvc].itemAtPosition(
                                                0,
                                                1).widget().setCurrentIndex(i)

                            elif ',' in value_list[j]:
                                type_mas = self.main_grid_list[
                                    bvc].itemAtPosition(0, 1).widget().count()
                                for i in range(type_mas):
                                    if self.main_grid_list[bvc].itemAtPosition(
                                            0, 1).widget().itemText(
                                                i) == value_list[j].split(
                                                    ', ')[0]:
                                        self.main_grid_list[
                                            bvc].itemAtPosition(
                                                0,
                                                1).widget().setCurrentIndex(i)

                                self.main_grid_list[bvc].addWidget(
                                    self.traction_lbl_list[bvc],
                                    1,
                                    0,
                                    alignment=QtCore.Qt.AlignLeft)
                                self.main_grid_list[bvc].addWidget(
                                    self.traction_list[bvc],
                                    1,
                                    1,
                                    alignment=QtCore.Qt.AlignLeft)
                                self.main_grid_list[bvc].addWidget(
                                    self.xyz_1_list_main[bvc][0],
                                    1,
                                    2,
                                    alignment=QtCore.Qt.AlignLeft)
                                self.main_grid_list[bvc].addWidget(
                                    self.xyz_1_list_main[bvc][1],
                                    1,
                                    3,
                                    alignment=QtCore.Qt.AlignLeft)
                                self.main_grid_list[bvc].addWidget(
                                    self.xyz_1_list_main[bvc][2],
                                    1,
                                    4,
                                    alignment=QtCore.Qt.AlignLeft)

                                self.main_grid_list[bvc].addWidget(
                                    self.pressure_lbl_list[bvc],
                                    2,
                                    0,
                                    alignment=QtCore.Qt.AlignLeft)
                                self.main_grid_list[bvc].addWidget(
                                    self.pressure_list[bvc],
                                    2,
                                    1,
                                    alignment=QtCore.Qt.AlignLeft)
                                self.main_grid_list[bvc].addWidget(
                                    self.koord_list[bvc],
                                    2,
                                    2,
                                    alignment=QtCore.Qt.AlignLeft)

                                self.main_grid_list[bvc].addWidget(
                                    self.value_lbl_list[bvc],
                                    3,
                                    0,
                                    alignment=QtCore.Qt.AlignLeft)
                                self.main_grid_list[bvc].addWidget(
                                    self.value_list[bvc],
                                    3,
                                    1,
                                    alignment=QtCore.Qt.AlignLeft)
                                self.main_grid_list[bvc].addWidget(
                                    self.xyz_2_list_main[bvc][0],
                                    3,
                                    2,
                                    alignment=QtCore.Qt.AlignLeft)
                                self.main_grid_list[bvc].addWidget(
                                    self.xyz_2_list_main[bvc][1],
                                    3,
                                    3,
                                    alignment=QtCore.Qt.AlignLeft)
                                self.main_grid_list[bvc].addWidget(
                                    self.xyz_2_list_main[bvc][2],
                                    3,
                                    4,
                                    alignment=QtCore.Qt.AlignLeft)
                                self.table.setRowHeight(bvc + 3, 120)

                                # traction
                                traction_mas = self.main_grid_list[
                                    bvc].itemAtPosition(1, 1).widget().count()
                                for i in range(traction_mas):
                                    if self.main_grid_list[bvc].itemAtPosition(
                                            1, 1).widget().itemText(
                                                i) == value_list[j].split(
                                                    ', ')[1]:
                                        self.main_grid_list[
                                            bvc].itemAtPosition(
                                                1,
                                                1).widget().setCurrentIndex(i)

                                self.main_grid_list[bvc].itemAtPosition(
                                    1, 2).widget().setText(
                                        value_list[j].split(', ')[2])
                                self.main_grid_list[bvc].itemAtPosition(
                                    1, 3).widget().setText(
                                        value_list[j].split(', ')[3])
                                self.main_grid_list[bvc].itemAtPosition(
                                    1, 4).widget().setText(
                                        value_list[j].split(', ')[4])

                                # pressure
                                pressure_mas = self.main_grid_list[
                                    bvc].itemAtPosition(2, 1).widget().count()
                                for i in range(pressure_mas):
                                    if self.main_grid_list[bvc].itemAtPosition(
                                            2, 1).widget().itemText(
                                                i) == value_list[j].split(
                                                    ', ')[5]:
                                        self.main_grid_list[
                                            bvc].itemAtPosition(
                                                2,
                                                1).widget().setCurrentIndex(i)

                                self.main_grid_list[bvc].itemAtPosition(
                                    2, 2).widget().setText(
                                        value_list[j].split(', ')[6])

                                # value
                                value_mas = self.main_grid_list[
                                    bvc].itemAtPosition(3, 1).widget().count()
                                for i in range(value_mas):
                                    if self.main_grid_list[bvc].itemAtPosition(
                                            3, 1).widget().itemText(
                                                i) == value_list[j].split(
                                                    ', ')[7]:
                                        self.main_grid_list[
                                            bvc].itemAtPosition(
                                                3,
                                                1).widget().setCurrentIndex(i)

                                self.main_grid_list[bvc].itemAtPosition(
                                    3, 2).widget().setText(
                                        value_list[j].split(', ')[8])
                                self.main_grid_list[bvc].itemAtPosition(
                                    3, 3).widget().setText(
                                        value_list[j].split(', ')[9])
                                self.main_grid_list[bvc].itemAtPosition(
                                    3, 4).widget().setText(
                                        value_list[j].split(', ')[10])

                    self.main_w = QWidget()
                    self.main_w.setLayout(self.main_grid)
                    self.table.setCellWidget(k, 0, el_p_lbl)
                    self.table.setCellWidget(k, 1, self.main_w)

                    k = k + 1
                    j = j + 1
                    bvc = bvc + 1

                btnSave = QPushButton()
                btnSave.setFixedSize(80, 25)
                btnSave.clicked.connect(self.on_btnSave_clicked)

                if self.interface_lng_val == 'Russian':
                    btnSave.setText("Сохранить")
                elif self.interface_lng_val == 'English':
                    btnSave.setText("Save")

                vbox = QVBoxLayout()
                vbox.addWidget(self.table)
                vbox.addWidget(btnSave)

                for bvc in range(len(self.type_list_main)):
                    self.type_chng(self.type_list_main, bvc)

                # ---------------------Размещение на форме всех компонентов-------------------------

                form = QFormLayout()
                form.addRow(vbox)
                self.setLayout(form)
Пример #51
0
    def createUI(self):
        vl = VLayout()
        self.setLayout(vl)

        # Wifi groupbox
        self.gbWifi = QGroupBox("WiFi")
        self.gbWifi.setCheckable(True)
        self.gbWifi.setChecked(False)
        flWifi = QFormLayout()
        self.leAP = QLineEdit()
        self.leAPPwd = QLineEdit()
        self.leAPPwd.setEchoMode(QLineEdit.Password)
        flWifi.addRow("SSID", self.leAP)
        flWifi.addRow("Password", self.leAPPwd)
        self.gbWifi.setLayout(flWifi)

        # Recovery Wifi groupbox
        self.gbRecWifi = QGroupBox("Recovery WiFi")
        self.gbRecWifi.setCheckable(True)
        self.gbRecWifi.setChecked(False)
        flRecWifi = QFormLayout()
        lbRecAP = QLabel("Recovery")
        lbRecAP.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        lbRecAPPwd = QLabel("a1b2c3d4")
        lbRecAPPwd.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        flRecWifi.addRow("SSID", lbRecAP)
        flRecWifi.addRow("Password", lbRecAPPwd)
        self.gbRecWifi.setLayout(flRecWifi)

        vl_wifis = VLayout(0)
        vl_wifis.addWidgets([self.gbWifi, self.gbRecWifi])

        # MQTT groupbox
        self.gbMQTT = QGroupBox("MQTT")
        self.gbMQTT.setCheckable(True)
        self.gbMQTT.setChecked(False)
        flMQTT = QFormLayout()
        self.leBroker = QLineEdit()
        self.sbPort = SpinBox()
        self.sbPort.setValue(1883)
        self.leTopic = QLineEdit()
        self.leTopic.setText("tasmota")
        self.leFullTopic = QLineEdit()
        self.leFullTopic.setText("%prefix%/%topic%/")
        self.leFriendlyName = QLineEdit()
        self.leMQTTUser = QLineEdit()
        self.leMQTTPass = QLineEdit()
        self.leMQTTPass.setEchoMode(QLineEdit.Password)

        flMQTT.addRow("Host", self.leBroker)
        flMQTT.addRow("Port", self.sbPort)
        flMQTT.addRow("Topic", self.leTopic)
        flMQTT.addRow("FullTopic", self.leFullTopic)
        flMQTT.addRow("FriendlyName", self.leFriendlyName)
        flMQTT.addRow("User [optional]", self.leMQTTUser)
        flMQTT.addRow("Password [optional]", self.leMQTTPass)
        self.gbMQTT.setLayout(flMQTT)

        # Module/template groupbox
        self.gbModule = GroupBoxV("Module/template")
        self.gbModule.setCheckable(True)
        self.gbModule.setChecked(False)

        hl_m_rb = HLayout()
        self.rbModule = QRadioButton("Module")
        self.rbModule.setChecked(True)
        self.rbTemplate = QRadioButton("Template")
        hl_m_rb.addWidgets([self.rbModule, self.rbTemplate])

        self.rbgModule = QButtonGroup(self.gbModule)
        self.rbgModule.addButton(self.rbModule, 0)
        self.rbgModule.addButton(self.rbTemplate, 1)

        self.cbModule = QComboBox()
        for mod_id, mod_name in modules.items():
            self.cbModule.addItem(mod_name, mod_id)

        self.leTemplate = QLineEdit()
        self.leTemplate.setPlaceholderText("Paste template string here")
        self.leTemplate.setVisible(False)

        self.gbModule.addLayout(hl_m_rb)
        self.gbModule.addWidgets([self.cbModule, self.leTemplate])
        self.rbgModule.buttonClicked[int].connect(self.setModuleMode)

        # layout all widgets
        hl_wifis_mqtt = HLayout(0)
        hl_wifis_mqtt.addLayout(vl_wifis)
        hl_wifis_mqtt.addWidget(self.gbMQTT)

        vl.addLayout(hl_wifis_mqtt)
        vl.addWidget(self.gbModule)

        btns = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Close)
        btns.accepted.connect(self.accept)
        btns.rejected.connect(self.reject)
        vl.addWidget(btns)
Пример #52
0
class MainWindow(QWidget):
    finished_signal = pyqtSignal(list, list, list)

    def __init__(self):
        super().__init__()
        self.main_widget = QWidget()
        self.main_widget.setGeometry(450, 100, 950, 800)
        self.main_widget.setWindowTitle("MULTI-STIMULI PROCESS")
        self.main_widget.setFont((QFont("Amble", 11)))
        self.main_widget.setFixedSize(1000, 650)
        # self.main_widget.setMinimumSize(900, 900)
        # self.main_widget.setMaximumSize(900, 600)

        # CREATING SELECTIONS...

        self.stimodour1 = QCheckBox()
        self.stimodour2 = QCheckBox()
        self.whisker = QCheckBox()
        self.auditory = QCheckBox()
        self.visual = QCheckBox()
        self.check_list = [
            self.stimodour1, self.stimodour2, self.whisker, self.auditory,
            self.visual
        ]
        self.odour1_flag = 0  # Creating check flag for experiments
        self.odour2_flag = 0
        self.whisker_flag = 0
        self.auditory_flag = 0
        self.visual_flag = 0
        # CREATING GUI...

        self.titlebox = QHBoxLayout()
        self.gap = QLabel("")
        self.types = QLabel("Types of Stimulations")
        self.types.setFont(QFont("Amble", 11, QFont.Bold))
        self.types.setAlignment(Qt.AlignLeft)
        self.delay = QLabel("Delay")
        self.delay.setFont(QFont("Amble", 11, QFont.Bold))
        self.delay.setAlignment(Qt.AlignHCenter)
        self.stim_length = QLabel("Length of Stim")
        self.stim_length.setFont(QFont("Amble", 11, QFont.Bold))
        self.stim_length.setAlignment(Qt.AlignCenter)
        self.offtime = QLabel("Off Time")
        self.offtime.setFont(QFont("Amble", 11, QFont.Bold))
        self.offtime.setAlignment(Qt.AlignHCenter)
        self.frequency = QLabel("Frequency")
        self.frequency.setFont(QFont("Amble", 11, QFont.Bold))
        self.frequency.setAlignment(Qt.AlignHCenter)
        self.amplitude = QLabel("Amplitude")
        self.amplitude.setFont(QFont("Amble", 11, QFont.Bold))
        self.amplitude.setAlignment(Qt.AlignHCenter)
        self.repetition = QLabel("Repetition")
        self.repetition.setFont(QFont("Amble", 11, QFont.Bold))
        self.repetition.setAlignment(Qt.AlignHCenter)

        # CREATING GUI...

        self.titlebox.addWidget(self.types)
        self.titlebox.addWidget(self.delay)
        self.titlebox.addWidget(self.stim_length)
        self.titlebox.addWidget(self.offtime)
        self.titlebox.addWidget(self.frequency)
        self.titlebox.addWidget(self.amplitude)
        self.titlebox.addWidget(self.repetition)

        # CREATING GUI...

        self.boxodour1 = QHBoxLayout()
        self.odour1 = QLabel("   Odour 1")
        self.odour1.setFont(QFont("Amble", 11))
        self.odour2 = QLabel("   Odour 2")
        self.odour2.setFont(QFont("Amble", 11))
        self.odour1buton1 = QSpinBox()
        self.odour1buton2 = QSpinBox()
        self.odour1buton3 = QSpinBox()
        self.odour1buton4 = QSpinBox()
        self.odour1buton5 = QDoubleSpinBox()
        self.odour1buton6 = QSpinBox()
        self.odour1buton4.setEnabled(0)
        self.odour1buton5.setEnabled(0)

        self.boxodour1.addWidget(self.odour1)
        self.boxodour1.addWidget(self.odour1buton1)
        self.boxodour1.addWidget(self.odour1buton2)
        self.boxodour1.addWidget(self.odour1buton3)
        self.boxodour1.addWidget(self.odour1buton4)
        self.boxodour1.addWidget(self.odour1buton5)
        self.boxodour1.addWidget(self.odour1buton6)

        # CREATING GUI...

        self.odour2buton1 = QSpinBox()
        self.odour2buton2 = QSpinBox()
        self.odour2buton3 = QSpinBox()
        self.odour2buton4 = QSpinBox()
        self.odour2buton5 = QDoubleSpinBox()
        self.odour2buton6 = QSpinBox()
        self.odour2buton4.setEnabled(0)
        self.odour2buton5.setEnabled(0)

        self.boxodour2 = QHBoxLayout()
        self.boxodour2.addWidget(self.odour2)
        self.boxodour2.addWidget(self.odour2buton1)
        self.boxodour2.addWidget(self.odour2buton2)
        self.boxodour2.addWidget(self.odour2buton3)
        self.boxodour2.addWidget(self.odour2buton4)
        self.boxodour2.addWidget(self.odour2buton5)
        self.boxodour2.addWidget(self.odour2buton6)

        # CREATING GUI...

        self.boxwhisker = QHBoxLayout()
        self.label2 = QLabel("   Whisker")
        self.label2.setFont(QFont("Amble", 11))
        self.buton2 = QSpinBox()
        self.buton6 = QSpinBox()
        self.buton9 = QSpinBox()
        self.buton12 = QSpinBox()
        self.buton15 = QDoubleSpinBox()
        self.buton18 = QSpinBox()

        self.boxwhisker.addWidget(self.label2)
        self.boxwhisker.addWidget(self.buton2)
        self.boxwhisker.addWidget(self.buton6)
        self.boxwhisker.addWidget(self.buton9)
        self.boxwhisker.addWidget(self.buton12)
        self.boxwhisker.addWidget(self.buton15)
        self.boxwhisker.addWidget(self.buton18)

        # CREATING GUI...

        self.box_auditory = QHBoxLayout()
        self.label3 = QLabel("   Auditory")
        self.label3.setFont(QFont("Amble", 11))
        self.buton3 = QSpinBox()
        self.buton7 = QSpinBox()
        self.buton10 = QSpinBox()
        self.buton13 = QSpinBox()
        self.buton16 = QDoubleSpinBox()
        self.buton19 = QSpinBox()

        self.box_auditory.addWidget(self.label3)
        self.box_auditory.addWidget(self.buton3)
        self.box_auditory.addWidget(self.buton7)
        self.box_auditory.addWidget(self.buton10)
        self.box_auditory.addWidget(self.buton13)
        self.box_auditory.addWidget(self.buton16)
        self.box_auditory.addWidget(self.buton19)

        # CREATING GUI...

        self.visual_box = QHBoxLayout()
        self.label4 = QLabel("   Visual")
        self.label4.setFont(QFont("Amble", 11))
        self.buton4 = QSpinBox()
        self.buton8 = QSpinBox()
        self.buton11 = QSpinBox()
        self.buton14 = QSpinBox()
        self.buton17 = QDoubleSpinBox()
        self.buton20 = QSpinBox()

        self.butonlist = [
            self.odour1buton1, self.odour1buton2, self.odour1buton3,
            self.odour1buton6, self.odour2buton1, self.odour2buton2,
            self.odour2buton3, self.odour2buton6, self.buton2, self.buton6,
            self.buton9, self.buton12, self.buton15, self.buton18, self.buton3,
            self.buton7, self.buton10, self.buton13, self.buton16,
            self.buton19, self.buton4, self.buton8, self.buton11, self.buton14,
            self.buton17, self.buton20
        ]

        self.visual_box.addWidget(self.label4)
        self.visual_box.addWidget(self.buton4)
        self.visual_box.addWidget(self.buton8)
        self.visual_box.addWidget(self.buton11)
        self.visual_box.addWidget(self.buton14)
        self.visual_box.addWidget(self.buton17)
        self.visual_box.addWidget(self.buton20)

        # CREATING START-CANCEL BUTTONS

        self.boxofcontrol = QHBoxLayout()
        self.start = QPushButton("START")
        self.start.setFixedSize(100, 28)
        self.cancel = QPushButton("CANCEL")
        self.cancel.setFixedSize(100, 28)
        self.cancel.clicked.connect(self.click_cancel)
        self.start.clicked.connect(self.function_start)
        self.boxofcontrol.addWidget(self.start)
        self.boxofcontrol.addWidget(self.cancel)

        # LAYOUT of BOXES (RELATED TO GUI)

        self.form = QFormLayout()
        self.form.addRow(self.gap)
        self.form.addRow(self.titlebox)
        self.form.addRow(self.gap)
        self.form.addRow(self.stimodour1, self.boxodour1)
        self.form.addRow(self.gap)
        self.form.addRow(self.stimodour2, self.boxodour2)
        self.form.addRow(self.gap)
        self.form.addRow(self.whisker, self.boxwhisker)
        self.form.addRow(self.gap)
        self.form.addRow(self.visual, self.box_auditory)
        self.form.addRow(self.gap)
        self.form.addRow(self.auditory, self.visual_box)
        self.form.addRow(self.gap)
        self.form.addRow(self.gap)
        self.form.addRow(self.gap)
        self.form.addRow(self.gap)
        self.form.addRow(self.boxofcontrol)
        self.main_widget.setLayout(self.form)
        self.finished_signal.connect(self.plotting_figure)

        self.main_widget.show()

        # THE MOST IMPORTANT PART: START, THREAD AND CANCEL !

    def function_start(self):

        self.running = 1  # FLAG FOR General_THREAD RUN
        self.running_whisker = 1  # FLAG FOR Whisker_THREAD RUN
        GPIO.setwarnings(False)
        self.flag_control()  #Flag of selections control
        self.get_value()  #assign value which received from user
        self.repetition_control()
        self.set_unabled()  # MAKE DISABLED OF SELECTIONS
        self.data_valve1, self.data_valve2, self.data_whisker = [0], [0], [0]
        self.data_auditory, self.data_visual = [0], [
            0
        ]  #collecting Rpi's pin status in list
        # START OF EXPERIMENT

        self.general_thread = General_Thread()
        self.general_thread.start()
        self.whisker_thread = Whisker_Thread()
        self.whisker_thread.start()

    def flag_control(self):

        if self.stimodour1.isChecked():
            self.odour1_flag = 1
        if self.stimodour2.isChecked():
            self.odour2_flag = 1
        if self.whisker.isChecked():
            self.whisker_flag = 1
        if self.auditory.isChecked():
            self.auditory_flag = 1
        if self.visual.isChecked():
            self.visual_flag = 1

    def get_value(self):
        self.delay_odour1 = self.odour1buton1.value(
        )  # Getting values from user's selections
        self.length_odour1 = self.odour1buton2.value()
        self.offtime_odour1 = self.odour1buton3.value()
        self.repetition_odour1 = self.odour1buton6.value()

        self.delay_odour2 = self.odour2buton1.value(
        )  # Getting values from user's selections
        self.length_odour2 = self.odour2buton2.value()
        self.offtime_odour2 = self.odour2buton3.value()
        self.repetition_odour2 = self.odour2buton6.value()

        self.delay_whisker = self.buton2.value(
        )  # Getting values from user's selections
        self.length_whisker = self.buton6.value()
        self.offtime_whisker = self.buton9.value()
        self.frequency_whisker = self.buton12.value()
        self.amplitude_whisker = self.buton15.value()
        self.repetition_whisker = self.buton18.value()

        self.delay_auditory = self.buton3.value(
        )  # Getting values from user's selections
        self.length_auditory = self.buton7.value()
        self.offtime_auditory = self.buton10.value()
        self.frequency_auditory = self.buton13.value()
        self.amplitude_auditory = self.buton16.value()
        self.repetition_auditory = self.buton19.value()

        self.delay_visual = self.buton4.value(
        )  # Getting values from user's selections
        self.length_visual = self.buton8.value()
        self.offtime_visual = self.buton11.value()
        self.frequency_visual = self.buton14.value()
        self.amplitude_visual = self.buton17.value()
        self.repetition_visual = self.buton20.value()

        self.totaltime_odour1 = self.delay_odour1 + self.length_odour1 + self.offtime_odour1
        self.totaltime_odour2 = self.delay_odour2 + self.length_odour2 + self.offtime_odour2
        self.totaltime_auditory = self.delay_auditory + self.length_auditory + self.offtime_auditory
        self.totaltime_whisker = self.delay_whisker + self.length_whisker + self.offtime_whisker

    def repetition_control(self):
        if self.repetition_odour1 == 0:
            self.odour1_flag = 0
        if self.repetition_odour2 == 0:
            self.odour2_flag = 0
        if self.repetition_visual == 0:
            self.visual_flag = 0
        if self.repetition_auditory == 0:
            self.auditory_flag = 0
        if self.repetition_whisker == 0:
            self.whisker_flag = 0

    def set_unabled(self):
        for i in self.check_list:
            i.setEnabled(0)
        self.start.setEnabled(0)  # start and cancel unabled!
        self.cancel.setEnabled(0)

    def plotting_figure(self):
        datacompare = max([
            len(mW.data_valve1),
            len(mW.data_valve2),
            len(mW.data_whisker),
            len(mW.data_auditory),
            len(mW.data_visual)
        ])

        data_list = [
            mW.data_valve1, mW.data_valve2, mW.data_whisker, mW.data_auditory,
            mW.data_visual
        ]
        for i in data_list:
            i += [0] * (datacompare - len(i))
        fig, axes = plt.subplots(3, 1, figsize=(18, 7))

        fig.suptitle("Stimulus-Time Graph")
        axes[0].plot(mW.data_valve1, color='red', drawstyle='steps-pre')
        axes[0].set_ylabel('Odour1')
        axes[0].set_xticks(list(range(0, datacompare)))
        axes[0].set_yticks([0, 1])

        axes[1].plot(mW.data_valve2, color='green', drawstyle='steps-pre')
        axes[1].set_ylabel('Odour2')
        axes[1].set_xticks(list(range(0, datacompare)))
        axes[1].set_yticks([0, 1])
        axes[2].plot(mW.data_whisker, color='blue', drawstyle='steps-pre')
        axes[2].set_ylabel('Whisker')
        axes[2].set_xlabel('Time')
        axes[2].set_xticks(list(range(0, datacompare)))
        axes[2].set_yticks([0, 1])
        plt.subplots_adjust(top=0.94,
                            hspace=0.29,
                            bottom=0.09,
                            left=0.048,
                            right=0.96)
        plt.show()

    def creating_csv(self):
        self.file_name = datetime.ctime(datetime.now())
        self.timecompare = max([
            len(mW.data_valve1),
            len(mW.data_valve2),
            len(mW.data_whisker),
            len(mW.data_auditory),
            len(mW.data_visual)
        ])
        self.time = list(range(0, self.timecompare))
        finished_data = list(
            zip_longest(self.time[1:],
                        mW.data_valve1[1:],
                        mW.data_valve2[1:],
                        mW.data_whisker[1:],
                        mW.data_auditory[1:],
                        mW.data_visual[1:],
                        fillvalue=0))

        header = ['Time', 'Odour1', 'Odour2', 'Whisker', 'Auditive', 'Visual']
        with open(''.join([self.file_name, '.csv']), 'w') as csv_file:
            writer = csv.writer(csv_file)
            writer.writerow(header)
            for i in finished_data:
                writer.writerow(i)

    def function_cancel(self):

        self.set_enabled()
        global running
        global running_whisker
        self.running = 0
        self.running_whisker = 0
        #mW.general_thread.quit()  # thread-safe quit
        mW.whisker_thread.quit()

    def set_enabled(self):
        # MAKE ENABLED OF SELECTIONS
        for i in self.check_list:
            i.setEnabled(1)
        self.start.setEnabled(1)
        self.cancel.setEnabled(1)

    def click_cancel(self):
        for i in self.butonlist:  # When user wants to reset selections and click cancel values are changed as 0
            i = i.setValue(0)
        for i in self.check_list:
            i = i.setChecked(0)
Пример #53
0
	def __init__(self, parent=None):
		super(lineEditDemo, self).__init__(parent)
		e1 = QLineEdit()
		e1.setValidator( QIntValidator() )
		e1.setMaxLength(4)
		e1.setAlignment( Qt.AlignRight )
		e1.setFont( QFont("Arial",20))
		e2 = QLineEdit()
		e2.setValidator( QDoubleValidator(0.99,99.99,2))
		flo = QFormLayout()
		flo.addRow("integer validator", e1)
		flo.addRow("Double validator",e2)
		e3 = QLineEdit()
		e3.setInputMask('+99_9999_999999')
		flo.addRow("Input Mask",e3)
		e4 = QLineEdit()
		e4.textChanged.connect( self.textchanged )
		flo.addRow("Text changed",e4)
		e5 = QLineEdit()
		e5.setEchoMode( QLineEdit.Password )
		flo.addRow("Password",e5)
		e6 = QLineEdit("Hello PyQt5")
		e6.setReadOnly(True)
		flo.addRow("Read Only",e6 )
		e5.editingFinished.connect( self.enterPress )
		self.setLayout(flo)
		self.setWindowTitle("QLineEdit例子")
Пример #54
0
class UIExportLayers(object):
    def __init__(self):
        self.mainDialog = exportlayersdialog.ExportLayersDialog()
        self.mainLayout = QVBoxLayout(self.mainDialog)
        self.formLayout = QFormLayout()
        self.documentLayout = QVBoxLayout()
        self.directorySelectorLayout = QHBoxLayout()
        self.optionsLayout = QVBoxLayout()
        self.resolutionLayout = QHBoxLayout()

        self.refreshButton = QPushButton("Refresh")
        self.widgetDocuments = QListWidget()
        self.directoryTextField = QLineEdit()
        self.directoryDialogButton = QPushButton("...")
        self.exportFilterLayersCheckBox = QCheckBox("Export filter layers")
        self.batchmodeCheckBox = QCheckBox("Export in batchmode")
        self.ignoreInvisibleLayersCheckBox = QCheckBox(
            "Ignore invisible layers")
        self.xResSpinBox = QSpinBox()
        self.yResSpinBox = QSpinBox()
        self.formatsComboBox = QComboBox()

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)

        self.kritaInstance = krita.Krita.instance()
        self.documentsList = []

        self.directoryTextField.setReadOnly(True)
        self.batchmodeCheckBox.setChecked(True)
        self.directoryDialogButton.clicked.connect(self._selectDir)
        self.widgetDocuments.currentRowChanged.connect(self._setResolution)
        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.setSizeAdjustPolicy(
            QAbstractScrollArea.AdjustToContents)

    def initialize(self):
        self.loadDocuments()

        self.xResSpinBox.setRange(1, 10000)
        self.yResSpinBox.setRange(1, 10000)

        self.formatsComboBox.addItem("jpeg")
        self.formatsComboBox.addItem("png")

        self.documentLayout.addWidget(self.widgetDocuments)
        self.documentLayout.addWidget(self.refreshButton)

        self.directorySelectorLayout.addWidget(self.directoryTextField)
        self.directorySelectorLayout.addWidget(self.directoryDialogButton)

        self.optionsLayout.addWidget(self.exportFilterLayersCheckBox)
        self.optionsLayout.addWidget(self.batchmodeCheckBox)
        self.optionsLayout.addWidget(self.ignoreInvisibleLayersCheckBox)

        self.resolutionLayout.addWidget(self.xResSpinBox)
        self.resolutionLayout.addWidget(self.yResSpinBox)

        self.formLayout.addRow('Documents', self.documentLayout)
        self.formLayout.addRow('Initial directory',
                               self.directorySelectorLayout)
        self.formLayout.addRow('Export options', self.optionsLayout)
        self.formLayout.addRow('Resolution', self.resolutionLayout)
        self.formLayout.addRow('Images Extensions', self.formatsComboBox)

        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("Export Layers")
        self.mainDialog.setSizeGripEnabled(True)
        self.mainDialog.show()
        self.mainDialog.activateWindow()

    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 not selectedDocuments:
            self.msgBox.setText("Select one document.")
        elif not self.directoryTextField.text():
            self.msgBox.setText("Select the initial directory.")
        else:
            self.export(selectedDocuments[0])
            self.msgBox.setText("All layers has been exported.")
        self.msgBox.exec_()

    def mkdir(self, directory):
        target_directory = self.directoryTextField.text() + directory
        if os.path.exists(target_directory) and os.path.isdir(
                target_directory):
            return

        try:
            os.makedirs(target_directory)
        except OSError as e:
            raise e

    def export(self, document):
        Application.setBatchmode(self.batchmodeCheckBox.isChecked())

        documentName = document.fileName() if document.fileName(
        ) else 'Untitled'
        fileName, extension = os.path.splitext(os.path.basename(documentName))
        self.mkdir('/' + fileName)

        self._exportLayers(document.rootNode(),
                           self.formatsComboBox.currentText(), '/' + fileName)
        Application.setBatchmode(True)

    def _exportLayers(self, parentNode, fileFormat, parentDir):
        """ This method get all sub-nodes from the current node and export then in
            the defined format."""

        for node in parentNode.childNodes():
            newDir = ''
            if node.type() == 'grouplayer':
                newDir = os.path.join(parentDir, node.name())
                self.mkdir(newDir)
            elif not self.exportFilterLayersCheckBox.isChecked(
            ) and 'filter' in node.type():
                continue
            elif self.ignoreInvisibleLayersCheckBox.isChecked(
            ) and not node.visible():
                continue
            else:
                nodeName = node.name()
                _fileFormat = self.formatsComboBox.currentText()
                if '[jpeg]' in nodeName:
                    _fileFormat = 'jpeg'
                elif '[png]' in nodeName:
                    _fileFormat = 'png'

                layerFileName = '{0}{1}/{2}.{3}'.format(
                    self.directoryTextField.text(), parentDir, node.name(),
                    _fileFormat)
                node.save(layerFileName, self.xResSpinBox.value(),
                          self.yResSpinBox.value())

            if node.childNodes():
                self._exportLayers(node, fileFormat, newDir)

    def _selectDir(self):
        directory = QFileDialog.getExistingDirectory(self.mainDialog,
                                                     "Select a folder",
                                                     os.path.expanduser("~"),
                                                     QFileDialog.ShowDirsOnly)
        self.directoryTextField.setText(directory)

    def _setResolution(self, index):
        document = self.documentsList[index]
        self.xResSpinBox.setValue(document.width())
        self.yResSpinBox.setValue(document.height())
Пример #55
0
    def __init__(self, title):
        super(Window, self).__init__(None)

        comp_width = 299
        col_width = 350
        header_height = 25

        # OpenGL window.
        self.scene_window = SceneWindow()

        # GUI consists of three components laid out horizontally.

        # Component #1: parameter entry.
        # Parameter entry components are laid out vertically.
        pvlo = QVBoxLayout()

        param_text = QLabel(
            """<p align="center"><strong>Scene Parameters</strong></p>""")
        param_text.setFixedSize(col_width, header_height)

        pvlo.addWidget(param_text)

        flo_widget = QWidget()

        flo = QFormLayout()
        entry_fields = {}
        params = [
            "x_delta", "y_delta", "z_delta", "yaw", "pitch", "roll", "amb_int",
            "dir_int", "DirLight"
        ]
        for name in params:
            # See: https://www.tutorialspoint.com/pyqt/pyqt_qlineedit_widget.htm.
            edit = QLineEdit()
            edit.setFixedWidth(200)
            entry_fields[name] = edit
            if name in {"yaw", "pitch", "roll"}:
                name += " (deg.)"
            flo.addRow(name, edit)

        self.scene_window.entry_fields = entry_fields
        flo.setContentsMargins(0, 0, 0, 0)

        # See: https://www.tutorialspoint.com/pyqt/pyqt_qpushbutton_widget.htm.
        submit = QPushButton("Set Parameters")
        submit.setFixedWidth(comp_width)
        submit.clicked.connect(self.scene_window.set_entry_form_values)

        flo_widget.setLayout(flo)
        flo_widget.setFixedWidth(comp_width)

        pvlo.addWidget(flo_widget)
        pvlo.setAlignment(flo_widget, QtCore.Qt.AlignHCenter)
        pvlo.addWidget(submit)
        pvlo.setAlignment(submit, QtCore.Qt.AlignHCenter)

        # Component #2: scene and neural network predictions.
        vlo = QVBoxLayout()

        # Mode text.
        mode_text = QLabel(
            """<p align="center"><strong>Translate</strong></p>""")
        mode_text.setFixedSize(col_width, header_height)
        self.scene_window.mode_text = mode_text

        vlo.addWidget(mode_text)

        vlo.addWidget(self.scene_window)
        vlo.setAlignment(self.scene_window, QtCore.Qt.AlignHCenter)

        # Prediction text.
        pred_text = QLabel("<strong>Top Label</strong>: <br>"
                           "<strong>Top Probability</strong>: <br><br>"
                           "<strong>True Label</strong>: <br>"
                           "<strong>True Probability</strong>: ")
        self.scene_window.pred_text = pred_text
        pred_text.setFixedSize(comp_width, 100)
        pred_text.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)

        vlo.addWidget(pred_text)
        vlo.setAlignment(pred_text, QtCore.Qt.AlignHCenter)

        # Predict button.
        predict = QPushButton("Predict")
        predict.setFixedWidth(comp_width)
        predict.clicked.connect(self.scene_window.get_prediction)

        vlo.addWidget(predict)
        vlo.setAlignment(predict, QtCore.Qt.AlignHCenter)

        # Component #3: instructions.
        ivlo = QVBoxLayout()

        instructions_header = QLabel(
            """<p align="center"><strong>Instructions</strong></p>""")
        instructions_header.setFixedHeight(header_height)
        ivlo.addWidget(instructions_header)

        instructions_txt = open(INSTRUCTIONS_F).read()
        instructions = QLabel(instructions_txt)
        instructions.setAlignment(QtCore.Qt.AlignTop)
        instructions.setFixedWidth(col_width)
        instructions.setWordWrap(True)
        instructions.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)
        instructions.setOpenExternalLinks(True)

        ivlo.addWidget(instructions)

        # Combine three components.
        hlo = QHBoxLayout()
        hlo.addLayout(pvlo)
        hlo.setAlignment(pvlo, QtCore.Qt.AlignTop)
        hlo.addLayout(vlo)
        hlo.setAlignment(vlo, QtCore.Qt.AlignTop)
        hlo.addLayout(ivlo)
        hlo.setAlignment(ivlo, QtCore.Qt.AlignTop)

        self.setLayout(hlo)

        self.title = title
        self.setWindowTitle(self.title)
        self.setFixedHeight(525)

        self.scene_window.setFocus()
Пример #56
0
    def __init__(self, chan_name, group_name, config_value, s_freq):
        super().__init__()

        self.chan_name = chan_name
        self.group_name = group_name

        self.idx_l0 = QListWidget()
        self.idx_l1 = QListWidget()

        self.add_channels_to_list(self.idx_l0, add_ref=True)
        self.add_channels_to_list(self.idx_l1)

        self.idx_hp = QDoubleSpinBox()
        hp = config_value['hp']
        if hp is None:
            hp = 0
        self.idx_hp.setValue(hp)
        self.idx_hp.setSuffix(' Hz')
        self.idx_hp.setDecimals(1)
        self.idx_hp.setMaximum(s_freq / 2)
        self.idx_hp.setToolTip('0 means no filter')

        self.idx_lp = QDoubleSpinBox()
        lp = config_value['lp']
        if lp is None:
            lp = 0
        self.idx_lp.setValue(lp)
        self.idx_lp.setSuffix(' Hz')
        self.idx_lp.setDecimals(1)
        self.idx_lp.setMaximum(s_freq / 2)
        self.idx_lp.setToolTip('0 means no filter')

        self.idx_notch = QDoubleSpinBox()
        if 'notch' in config_value:  # for backward compatibility
            notch = config_value['notch']
        else:
            notch = None
        if notch is None:
            notch = 0
        self.idx_notch.setValue(notch)
        self.idx_notch.setSuffix(' Hz')
        self.idx_notch.setDecimals(1)
        self.idx_notch.setMaximum(s_freq / 2)
        self.idx_notch.setToolTip(
            '50Hz or 60Hz depending on the power line frequency. 0 means no filter'
        )

        self.idx_scale = QDoubleSpinBox()
        self.idx_scale.setValue(config_value['scale'])
        self.idx_scale.setSuffix('x')

        self.idx_reref = QPushButton('Average')
        self.idx_reref.clicked.connect(self.rereference)

        self.idx_color = QColor(config_value['color'])

        self.idx_demean = QCheckBox()
        self.idx_demean.setCheckState(Qt.Unchecked)
        if 'demean' in config_value:  # for backward compatibility
            if config_value['demean']:
                self.idx_demean.setCheckState(Qt.Checked)

        l_form = QFormLayout()
        l_form.addRow('High-Pass', self.idx_hp)
        l_form.addRow('Low-Pass', self.idx_lp)
        l_form.addRow('Notch Filter', self.idx_notch)

        r_form = QFormLayout()
        r_form.addRow('Reference', self.idx_reref)
        r_form.addRow('Scaling', self.idx_scale)
        r_form.addRow('Demean', self.idx_demean)

        l0_layout = QVBoxLayout()
        l0_layout.addWidget(QLabel('Active'))
        l0_layout.addWidget(self.idx_l0)

        l1_layout = QVBoxLayout()
        l1_layout.addWidget(QLabel('Reference'))
        l1_layout.addWidget(self.idx_l1)

        l_layout = QHBoxLayout()
        l_layout.addLayout(l0_layout)
        l_layout.addLayout(l1_layout)

        lr_form = QHBoxLayout()
        lr_form.addLayout(l_form)
        lr_form.addLayout(r_form)

        layout = QVBoxLayout()
        layout.addLayout(l_layout)
        layout.addLayout(lr_form)

        self.setLayout(layout)
Пример #57
0
    def __init__(self, configName, batch=False, fileType=True):
        super().__init__()
        self.configName = configName
        self.setTitle("Adjust Workingfile")
        formLayout = QFormLayout()
        self.setLayout(formLayout)
        self.crop = QCheckBox(i18n("Crop files before resize."))
        self.cmbFile = QComboBox()
        self.cmbFile.addItems(["png", "jpg", "webp"])
        self.resizeMethod = QComboBox()
        self.resizeMethod.addItems([
            i18n("Percentage"),
            i18n("DPI"),
            i18n("Maximum Width"),
            i18n("Maximum Height")
        ])
        self.resizeMethod.currentIndexChanged.connect(self.slot_set_enabled)
        self.spn_DPI = QSpinBox()
        self.spn_DPI.setMaximum(1200)
        self.spn_DPI.setSuffix(i18n(" DPI"))
        self.spn_DPI.setValue(72)
        self.spn_PER = QSpinBox()
        if batch is True:
            self.spn_PER.setMaximum(1000)
        else:
            self.spn_PER.setMaximum(100)
        self.spn_PER.setSuffix(" %")
        self.spn_PER.setValue(100)
        self.spn_width = QSpinBox()
        self.spn_width.setMaximum(99999)
        self.spn_width.setSuffix(" px")
        self.spn_width.setValue(800)
        self.spn_height = QSpinBox()
        self.spn_height.setMaximum(99999)
        self.spn_height.setSuffix(" px")
        self.spn_height.setValue(800)

        if batch is False:
            formLayout.addRow("", self.crop)
        if fileType is True and configName != "TIFF":
            formLayout.addRow(i18n("File Type"), self.cmbFile)
        formLayout.addRow(i18n("Method:"), self.resizeMethod)
        formLayout.addRow(i18n("DPI:"), self.spn_DPI)
        formLayout.addRow(i18n("Percentage:"), self.spn_PER)
        formLayout.addRow(i18n("Width:"), self.spn_width)
        formLayout.addRow(i18n("Height:"), self.spn_height)
        self.slot_set_enabled()
Пример #58
-1
class CardinalityRestrictionForm(QDialog):
    """
    This class implements the form used to input domain/range restriction cardinalities.
    """
    def __init__(self, parent=None):
        """
        Initialize the form dialog.
        :type parent: QWidget
        """
        super().__init__(parent)
        self.minCardinalityValue = None
        self.maxCardinalityValue = None
        self.minCardinalityField = IntField(self)
        self.maxCardinalityField = IntField(self)
        self.minCardinalityField.setFixedWidth(80)
        self.maxCardinalityField.setFixedWidth(80)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
        self.mainLayout = QFormLayout(self)
        self.mainLayout.addRow('Min. cardinality', self.minCardinalityField)
        self.mainLayout.addRow('Max. cardinality', self.maxCardinalityField)
        self.mainLayout.addRow(self.buttonBox)
        self.setWindowTitle('Insert cardinality')
        self.setWindowIcon(QIcon(':/images/eddy'))
        self.setFixedSize(self.sizeHint())

        connect(self.buttonBox.accepted, self.validate)
        connect(self.buttonBox.rejected, self.reject)

    ####################################################################################################################
    #                                                                                                                  #
    #   SLOTS                                                                                                          #
    #                                                                                                                  #
    ####################################################################################################################

    @pyqtSlot()
    def validate(self):
        """
        Validate the form and trigger accept() if the form is valid.
        """
        if not isEmpty(self.minCardinalityField.text()) and not isEmpty(self.maxCardinalityField.text()):

            v1 = int(self.minCardinalityField.text())
            v2 = int(self.maxCardinalityField.text())

            if v1 > v2:
                msgbox = QMessageBox(self)
                msgbox.setIconPixmap(QPixmap(':/icons/warning'))
                msgbox.setWindowIcon(QIcon(':/images/eddy'))
                msgbox.setWindowTitle('Invalid range specified')
                msgbox.setText('Minimum cardinality {} must be lower or equal than Maximum cardinality {}'.format(v1, v2))
                msgbox.setStandardButtons(QMessageBox.Ok)
                msgbox.exec_()
                return

        if not isEmpty(self.minCardinalityField.text()):
            self.minCardinalityValue = int(self.minCardinalityField.text())
        if not isEmpty(self.maxCardinalityField.text()):
            self.maxCardinalityValue = int(self.maxCardinalityField.text())

        self.accept()