def create_data_group(self):
     """Creates group for holding specific choice data selection"""
     button_group = QButtonGroup(self)
     button_group.setExclusive(True)
     colecao_radio_button = QRadioButton('Coleção')
     self.partidas_radio_button = QRadioButton('Partidas')
     colecao_radio_button.setChecked(True)
     button_group.addButton(colecao_radio_button)
     button_group.addButton(self.partidas_radio_button)
     (self.min_date_picker,
      min_date_label) = create_date_picker('À Partir de:', self)
     (self.max_date_picker,
      max_date_label) = create_date_picker('Até:', self)
     self.min_date_picker.dateChanged.connect(
         self.max_date_picker.setMinimumDate)
     colecao_radio_button.toggled.connect(self.min_date_picker.setDisabled)
     colecao_radio_button.toggled.connect(self.max_date_picker.setDisabled)
     self.map_users_button = QPushButton(
         'Ver mapa de usuarios BGG -> Ludopedia', self)
     self.map_users_button.setEnabled(False)
     self.map_users_button.clicked.connect(self.user_map)
     colecao_radio_button.toggled.connect(self.map_users_button.setDisabled)
     group_box = QGroupBox('Dados')
     grid_layout = QGridLayout(group_box)
     grid_layout.addWidget(colecao_radio_button, 1, 1)
     grid_layout.addWidget(self.partidas_radio_button, 1, 2)
     grid_layout.addWidget(min_date_label, 2, 1)
     grid_layout.addWidget(self.min_date_picker, 2, 2)
     grid_layout.addWidget(max_date_label, 3, 1)
     grid_layout.addWidget(self.max_date_picker, 3, 2)
     grid_layout.addWidget(self.map_users_button, 4, 1, 1, 2)
     group_box.setLayout(grid_layout)
     return group_box
class Profile(QWidget):
    def __init__(self):
        QWidget.__init__(self, None)
        self.ui = Ui_Form()
        self.setFixedSize(710, 465)
        self.ui.setupUi(self)
        self.ui.piclabel.setPixmap(QPixmap("app/UI/pngegg.png"))
        self.ui.piclabel.setScaledContents(True)
        self.widget = QWidget()
        formlayout = QFormLayout()
        self.blayout = QHBoxLayout()
        self.vlayout = QVBoxLayout()
        self.groupBox = QGroupBox()
        self.ui.editButton.clicked.connect(self.editProfile)

    def refresh(self):
        self.updateProfile(self.user)

    def updateProfile(self, cur_user):
        self.user = cur_user
        self.ui.usernameLabel.setText(cur_user.getUsername())
        self.ui.nameLabel_2.setText(cur_user.getFirstName())
        self.ui.lastnameLabel_2.setText(cur_user.getLastName())
        self.ui.dateLabel_2.setText(cur_user.getBirthDate())
        self.ui.genderLabel_2.setText(cur_user.getGender())
        self.ui.heightLabel_2.setText(str(cur_user.getHeight()))
        age = int(date.today().strftime("%Y")) - int(
            cur_user.getBirthDate()[-4:])
        if cur_user.getGender() == "Male":
            bmr = 10 * cur_user.getWeight() + 6.25 * cur_user.getHeight(
            ) - 5 * age + 5
        else:
            bmr = 10 * cur_user.getWeight() + 6.25 * cur_user.getHeight(
            ) - 5 * age - 161
        cal_need = bmr * 1.375
        cal_need = int(cal_need)
        self.ui.calLabel_2.setText(str(cal_need) + " kcal")
        print(cal_need)

        self.recipes = []
        recipes_info = RECIPE_MODEL.getRecipeFromCreator(
            self.user.getUsername())
        for i in reversed(range(self.vlayout.count())):
            self.vlayout.itemAt(i).widget().setParent(None)

        for i in range(len(recipes_info)):
            self.recipes.append(
                RecipeInProfile(recipes_info[i], self.user, self))
            self.vlayout.addWidget(self.recipes[i])

        self.groupBox.setLayout(self.vlayout)
        self.ui.recipeScrollArea.setWidget(self.groupBox)
        self.ui.recipeScrollArea.setStyleSheet(
            "background-color:rgb(255, 187, 178)\n")
        self.ui.recipeScrollArea.setWidgetResizable(True)

    def editProfile(self):
        self.editPage = ProfileEdit(self.user, self)
        self.editPage.show()
class MainWindowUI:
    def setup_ui(self, win: QMainWindow) -> None:
        # ui widgets
        self.toolbar = QToolBar("main", parent=win)
        self.port_combobox1 = PortCombobox("")
        self.port_combobox2 = PortCombobox("")
        self.baudrate_combobox = QComboBox()
        self.monitor1 = QPlainTextEdit("")
        self.monitor2 = QPlainTextEdit("")
        self.btn_clear_monitor1 = QPushButton("Clear")
        self.btn_clear_monitor2 = QPushButton("Clear")
        self.group_monitor1 = QGroupBox("Monitor 1")
        self.group_monitor2 = QGroupBox("Monitor 2")

        # setup widgets
        self.monitor1.setReadOnly(True)
        self.monitor1.setLineWrapMode(QPlainTextEdit.NoWrap)
        self.monitor1.setUndoRedoEnabled(False)
        self.monitor2.setReadOnly(True)
        self.monitor2.setLineWrapMode(QPlainTextEdit.NoWrap)
        self.monitor2.setUndoRedoEnabled(False)
        self.baudrate_combobox.addItems([
            "300",
            "1200",
            "2400",
            "4800",
            "9600",
            "19200",
            "38400",
            "57600",
            "74880",
            "115200",
            "230400",
            "250000",
            "500000",
            "1000000",
            "2000000",
        ])
        self.baudrate_combobox.setCurrentText("9600")

        # setup layout
        win.addToolBar(self.toolbar)

        v_layout = QVBoxLayout()  # type:ignore
        v_layout.addWidget(self.monitor1)
        v_layout.addWidget(self.btn_clear_monitor1)
        self.group_monitor1.setLayout(v_layout)

        v_layout = QVBoxLayout()  # type:ignore
        v_layout.addWidget(self.monitor2)
        v_layout.addWidget(self.btn_clear_monitor2)
        self.group_monitor2.setLayout(v_layout)

        h_layout = QHBoxLayout()  # type:ignore
        h_layout.addWidget(self.group_monitor1)
        h_layout.addWidget(self.group_monitor2)
        central_widget = QWidget()
        central_widget.setLayout(h_layout)
        win.setCentralWidget(central_widget)
Exemple #4
0
    def create_calendar(self, conf_path, spec):
        group = QGroupBox(spec["title"])
        layout = QVBoxLayout()
        widget = DateField(self, conf_path)

        layout.addWidget(widget)
        group.setLayout(layout)

        self.layout.addWidget(group)
Exemple #5
0
    def create_multiselect(self, conf_path, spec):
        group = QGroupBox(spec["title"])
        layout = QVBoxLayout()
        widget = MultiSelect(self, conf_path, spec["enum"])

        layout.addWidget(widget)
        group.setLayout(layout)

        self.layout.addWidget(group)
Exemple #6
0
    def create_string_field(self, conf_path, spec):
        group = QGroupBox(spec["title"])
        layout = QVBoxLayout()
        widget = (TextAreaField(self, conf_path) if spec.get("sub_type")
                  == "text_area" else StringField(self, conf_path))

        layout.addWidget(widget)
        group.setLayout(layout)

        self.layout.addWidget(group)
 def __init__(self):
     super().__init__()
     self.layout = QHBoxLayout()
     i = 0
     self.names = []
     self.ebutons = []
     self.dbutons = []
     folder = './saved'
     #-------------Loading saved images from ./saved------------
     if (len(os.listdir(folder)) == 0):
         #print oput nothing saved
         self.label = QLabel("Nothing Saved")
         self.layout.addWidget(self.label)
     else:
         for filename in os.listdir(folder):
             self.names.append(filename)
             self.ebutons.append(i)
             self.dbutons.append(i)
             lay = QVBoxLayout()
             gbox = QGroupBox('Result' + str(i + 1))
             path = folder + "/" + filename
             with open(path, 'rb') as thefile:
                 imag = pickle.load(thefile)
             path += ".jpg"
             im = Image.open(
                 requests.get(imag['urls']['thumb'], stream=True).raw)
             im.save(path)
             self.ebutons[i] = QPushButton("Edit")
             self.ebutons[i].clicked.connect(
                 lambda state=i, a=i: self.editme(state))
             self.dbutons[i] = QPushButton("Delete")
             self.dbutons[i].clicked.connect(
                 lambda state=i, a=i: self.deleteme(state))
             pixmap = QPixmap(path)
             self.image = QLabel()
             self.image.setPixmap(pixmap)
             lay.addWidget(self.image)
             buts = QHBoxLayout()
             buts.addWidget(self.ebutons[i])
             buts.addWidget(self.dbutons[i])
             lay.addLayout(buts)
             gbox.setLayout(lay)
             self.layout.addWidget(gbox)
             try:
                 if os.path.isfile(path) or os.path.islink(path):
                     os.unlink(path)
                 elif os.path.isdir(path):
                     shutil.rmtree(path)
             except Exception as e:
                 print('Failed to delete %s. Reason: %s' % (file_path, e))
             i += 1
     print("done")
     self.setLayout(self.layout)
Exemple #8
0
 def _setup_room_widget(self, room: Room):
     _grp = QGroupBox(title=room.name)
     _layout = QGridLayout()
     _row_num = 0
     for _light in room.lights:
         _lc = LightControl(_light)
         self._light_ctrl.append(_lc)
         _lbl = QLabel(f" > {_light.name}")
         _layout.addWidget(_lbl, _row_num, 0)
         _layout.addWidget(_lc.toggle_btn, _row_num, 1)
         _layout.addWidget(_lc.show_color_picker_btn, _row_num, 2)
         _layout.addWidget(_lc.slider, _row_num, 3)
         _row_num += 1
     _grp.setLayout(_layout)
     return _grp
    def __init__(self, parent=None):
        super(Maker, self).__init__(parent)

        self.setWindowTitle("Project Maker")

        self.userFilepath = QLineEdit()
        self.userFilepath.setPlaceholderText("Your filepath here...")
        self.projName = QLineEdit()
        self.projName.setPlaceholderText("Your project name here...")
        self.makeButton = QPushButton("Create Project")
        self.fileSearchButton = QPushButton("...")
        self.fileSearchButton.setToolTip(
            "Search for a directory for your project")

        self.goProj = QRadioButton("Go Project")
        self.goProj.setToolTip("You will still need a go.mod file")
        self.pyProj = QRadioButton("Python Project")
        self.versionControlFiles = QCheckBox(
            "Create README.md and .gitignore?")
        self.versionControlFiles.setToolTip(
            "Creates the files used in online version control, such as Github")
        self.pyProj.setChecked(True)
        self.versionControlFiles.setChecked(True)

        projSelect = QGroupBox("Project Selection")
        projectOptions = QVBoxLayout()
        projectOptions.addWidget(self.pyProj)
        projectOptions.addWidget(self.goProj)
        projectOptions.addWidget(self.versionControlFiles)
        projectOptions.stretch(1)
        projSelect.setLayout(projectOptions)

        searchLayout = QHBoxLayout()
        searchLayout.addWidget(self.userFilepath)
        searchLayout.addWidget(self.fileSearchButton)
        searchLayout.stretch(1)

        layout = QVBoxLayout()
        layout.addLayout(searchLayout)
        layout.addWidget(self.projName)
        layout.addWidget(self.makeButton)
        layout.addWidget(self.fileSearchButton)
        layout.addWidget(projSelect)
        self.setLayout(layout)

        self.makeButton.clicked.connect(self.createFiles)
        self.fileSearchButton.clicked.connect(self.onClickFileSearch)
Exemple #10
0
class TabMain(QWidget):
    def __init__(self) -> None:
        super().__init__()
        # member
        self.pathname_line = PathLine()
        self.checkbox_save_to_file = QCheckBox("Save to File")

        self.t_button_open_filedialog = create_tool_button(
            is_text_beside_icon=True)
        self.t_button_step_mode = create_tool_button(fixed_width=250)
        self.t_button_cycle_mode = create_tool_button(fixed_width=250)
        self.t_button_only_lcr_mode = create_tool_button(fixed_width=250)
        self.t_button_lcr_state = create_tool_button(fixed_width=250)
        self.spinbox_interval = QSpinBox()

        self.group_save = QGroupBox("Save")
        self.group_mode = QGroupBox("Mode")
        self.group_lcr_state = QGroupBox("LCR Meter")
        self.group_measure_interval = QGroupBox("Measurement Interval")

        # setup
        self.spinbox_interval.setRange(1, 100000)
        self.checkbox_save_to_file.setEnabled(False)

        # setup layout
        f_layout_save = QFormLayout()
        f_layout_save.addRow("File Path", self.pathname_line)
        f_layout_save.addWidget(self.t_button_open_filedialog)
        f_layout_save.addRow(self.checkbox_save_to_file)
        self.group_save.setLayout(f_layout_save)

        v_layout_mode = AVBoxLayout()
        v_layout_mode.addWidget(self.t_button_step_mode)
        v_layout_mode.addWidget(self.t_button_cycle_mode)
        v_layout_mode.addWidget(self.t_button_only_lcr_mode)
        v_layout_mode.setAlignment(Qt.AlignHCenter)
        self.group_mode.setLayout(v_layout_mode)

        v_layout_lcr_state = AVBoxLayout()
        v_layout_lcr_state.addWidget(self.t_button_lcr_state)
        v_layout_lcr_state.setAlignment(Qt.AlignHCenter)
        self.group_lcr_state.setLayout(v_layout_lcr_state)

        f_layout_repeat = QFormLayout()
        f_layout_repeat.addRow("Interval",
                               add_unit(self.spinbox_interval, "msec"))
        self.group_measure_interval.setLayout(f_layout_repeat)

        v_layout = AVBoxLayout(self)
        v_layout.addWidget(self.group_save)
        v_layout.addWidget(self.group_mode)
        v_layout.addWidget(self.group_lcr_state)
        v_layout.addWidget(self.group_measure_interval)
 def create_login_group(self):
     """Create labels and line edits for providing BGG and ludopedia login information"""
     (self.bgg_user_line_edit,
      bgg_user_label) = self.create_qlineedit('Usuario BoardGameGeek:')
     (self.ludo_mail_line_edit,
      ludo_mail_label) = self.create_qlineedit('E-mail Ludopedia:')
     (self.ludo_pass_line_edit,
      ludo_pass_label) = self.create_qlineedit('Senha Ludopedia:')
     self.ludo_pass_line_edit.setEchoMode(QLineEdit.PasswordEchoOnEdit)
     group_box = QGroupBox('Login')
     grid_layout = QGridLayout(group_box)
     grid_layout.addWidget(bgg_user_label, 1, 1)
     grid_layout.addWidget(self.bgg_user_line_edit, 1, 2)
     grid_layout.addWidget(ludo_mail_label, 2, 1)
     grid_layout.addWidget(self.ludo_mail_line_edit, 2, 2)
     grid_layout.addWidget(ludo_pass_label, 3, 1)
     grid_layout.addWidget(self.ludo_pass_line_edit, 3, 2)
     group_box.setLayout(grid_layout)
     return group_box
Exemple #12
0
class MainWindowUI:
    def setup_ui(self, win: QMainWindow, settings: Settings) -> None:
        self.statusbar = CustomStatusBar(win)
        self.toolbar = AToolBar(win)
        self.tab = QTabWidget()
        self.tab_main = TabMain()
        self.tab_lcr = TabLCR()
        self.tab_stage_step = TabStageStep()
        self.tab_stage_cycle = TabStageCycle()
        self.console = QPlainTextEdit()
        self.group_measurements_data = QGroupBox("Measurements Data")

        self.tab.addTab(self.tab_main, "Test")
        self.tab.addTab(self.tab_lcr, "LCR Meter")
        self.tab.addTab(self.tab_stage_step, "Stage Controller")
        self.tab.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.console.setReadOnly(True)
        self.console.setLineWrapMode(QPlainTextEdit.NoWrap)
        # self.console.setUndoRedoEnabled(False)

        # setup settings
        self.console.setMaximumBlockCount(
            settings.console.maximum_number_of_line)
        self.tab_main.spinbox_interval.setValue(settings.main.measure_interval)
        self.tab_stage_step.int_slider.update_current_value(
            settings.stage_controller.maximum_speed)
        self.tab_stage_cycle.int_slider.update_current_value(
            settings.stage_controller.maximum_speed)

        # setup layout
        v_layout = AVBoxLayout()
        v_layout.addWidget(self.console)
        self.group_measurements_data.setLayout(v_layout)

        h_layout = AHBoxLayout()
        h_layout.addWidget(self.tab)
        h_layout.addWidget(self.group_measurements_data)
        central_widget = QWidget()
        central_widget.setLayout(h_layout)
        win.setCentralWidget(central_widget)
Exemple #13
0
    def _create_options_group_box(self) -> QGroupBox:
        """Returns the group of prediction options."""
        options_group_box = QGroupBox("Options")

        options_layout = QGridLayout()
        left_options = QGridLayout()
        right_options = QGridLayout()

        date_label = QLabel("Target Date:")
        self._target_date = QCalendarWidget()

        left_options.addWidget(date_label, 0, 0)
        left_options.addWidget(self._target_date, 1, 0, 1, 3)

        left_options.setColumnStretch(0, 1)

        self._model = QComboBox()
        self._model_info = QPlainTextEdit()
        self._model_info.setReadOnly(True)

        self._model.currentTextChanged.connect(self._refresh_model_info)

        self._refresh_lists()

        models_label = QLabel("Models:")
        info_label = QLabel("Model Information:")

        right_options.addWidget(models_label, 0, 0)
        right_options.addWidget(self._model, 1, 0)

        right_options.addWidget(info_label, 2, 0)
        right_options.addWidget(self._model_info, 3, 0)

        options_layout.addLayout(left_options, 0, 0)
        options_layout.addLayout(right_options, 0, 1)

        options_group_box.setLayout(options_layout)

        return options_group_box
Exemple #14
0
    def __init__(self, master):
        QDialog.__init__(self)
        self.setWindowTitle("Configuração")
        self.setFixedSize(200, 200)
        self.setWindowIcon(QIcon(r'images\icon6.ico'))
        self.setModal(True)

        button1 = QPushButton("Cancelar")
        button1.clicked.connect(self.closeDialog)
        button2 = QPushButton("Confirmar")
        button2.clicked.connect(lambda: self.saveAndClose(master))

        num_elementos = len(master.timedeltas)
        self.checkboxes = [0]*num_elementos
        for i in range(num_elementos):
            self.checkboxes[i] = QCheckBox(master.timedeltastr[i])

        # Organizando o layout
        grupo = QGroupBox("Incluir Precipitação Acumulada Em")
        grid = QGridLayout()
        for x in range(num_elementos):
            if x < num_elementos/2:
                grid.addWidget(self.checkboxes[x], x , 0)
            else:
                grid.addWidget(self.checkboxes[x], x - num_elementos/2, 1)
        #
        grupo.setLayout(grid)
        self.startCheckboxes(master)
        #
        sublayout = QHBoxLayout()
        sublayout.addWidget(button1)
        sublayout.addWidget(button2)
        #
        layout = QVBoxLayout()
        layout.addWidget(grupo)
        layout.addLayout(sublayout)
        self.setLayout(layout)
Exemple #15
0
class TabLCR(QWidget):
    def __init__(self) -> None:
        super().__init__()
        # member
        self.combobox_parameter1 = IM3536ParameterCombobox()
        self.combobox_parameter2 = IM3536ParameterCombobox()
        self.combobox_parameter3 = IM3536ParameterCombobox()
        self.combobox_parameter4 = IM3536ParameterCombobox()
        self.spinbox_measurements_num = QSpinBox()
        self.checkbox_parmanent = QCheckBox("Parmanent Measurement")
        self.checkbox_acquire_monitor_data = QCheckBox(
            "Acquire Voltage/Current Monitor Values")

        self.group_parameter = QGroupBox("Parameter")
        self.group_only_lcr = QGroupBox("Only LCR Meter Mode")
        self.group_option = QGroupBox("Option")

        # setup
        self.combobox_parameter1.setCurrentText(
            "Rs   (Equivalent series resistance)")
        self.combobox_parameter1.set_none_disabled(True)
        self.spinbox_measurements_num.setRange(1, 1000000000)
        self.checkbox_acquire_monitor_data.setChecked(True)
        self.checkbox_parmanent.setChecked(True)
        self.spinbox_measurements_num.setEnabled(False)
        self.group_only_lcr.setEnabled(False)

        # stup layout
        f_layout_parameter = QFormLayout()
        f_layout_parameter.addRow("1", self.combobox_parameter1)
        f_layout_parameter.addRow("2", self.combobox_parameter2)
        f_layout_parameter.addRow("3", self.combobox_parameter3)
        f_layout_parameter.addRow("4", self.combobox_parameter4)
        self.group_parameter.setLayout(f_layout_parameter)

        f_layout_only_lcr = QFormLayout()
        f_layout_only_lcr.addRow(self.checkbox_parmanent)
        f_layout_only_lcr.addRow("Number of Measurements",
                                 self.spinbox_measurements_num)
        self.group_only_lcr.setLayout(f_layout_only_lcr)

        f_layout_option = QFormLayout()
        f_layout_option.addRow(self.checkbox_acquire_monitor_data)
        self.group_option.setLayout(f_layout_option)

        v_layout = AVBoxLayout(self)
        v_layout.addWidget(self.group_parameter)
        v_layout.addWidget(self.group_only_lcr)
        v_layout.addWidget(self.group_option)
Exemple #16
0
    def __init__(self):
        super().__init__()

        # Declare Widgets
        self.homepage_label = QLabel('Home')
        self.search_label = QLabel('Find an Image!')
        self.srch_box = QLineEdit()  # input field for search
        self.srch_btn = QPushButton("Search")

        # Create U.I. Layout
        mbox = QVBoxLayout()

        vbox = QVBoxLayout()
        vbox.addWidget(self.homepage_label)
        vbox.addWidget(self.search_label)
        vbox.addWidget(self.srch_box)
        vbox.addWidget(self.srch_btn)

        gbox1 = QGroupBox()
        gbox1.setLayout(vbox)
        mbox.addWidget(gbox1)

        # Homes Images Layout
        images = []
        images = self.getHomepageImages()

        # Create layout for images
        vbox2 = QHBoxLayout()

        i = 0
        for img in images:
            self.label = QLabel()
            # pic = Image.open(requests.get(img['urls']['thumb'], stream=True).raw)

            pixmap1 = QPixmap(img)

            pixmap1 = pixmap1.scaled(300, 300, Qt.KeepAspectRatio)

            self.label.setPixmap(pixmap1)

            temp_vbox = QVBoxLayout()
            temp_vbox.addWidget(self.label)

            gbox2 = QGroupBox()
            gbox2.setLayout(temp_vbox)
            gbox2.setStyleSheet("background-color: grey")

            vbox2.addWidget(gbox2)
            i += 1

        gbox3 = QGroupBox()
        gbox3.setLayout(vbox2)
        mbox.addWidget(gbox3)
        self.setLayout(mbox)

        # Styling
        self.setStyleSheet("""
            color: orange;
            font-family: Comfortaa;
            """)
        self.srch_btn.setStyleSheet(":hover { background-color:cyan }")
        gbox1.setStyleSheet("""
            font-size: 18px
            """)

        # Listeners
        self.srch_btn.clicked.connect(self.find_images)
    def __init__(self,
                 parent: Optional[QWidget] = None,
                 url: str = '') -> None:
        super().__init__(parent, )

        if parent:
            self.setWindowTitle('Download Mod')
        else:
            self.setWindowTitle(getTitleString('Download Mod'))
            self.setAttribute(Qt.WA_DeleteOnClose)

        mainLayout = QVBoxLayout(self)
        mainLayout.setContentsMargins(5, 5, 5, 5)

        self.signals = DownloadWindowEvents(self)

        # URL input

        gbUrl = QGroupBox('Mod URL')
        gbUrlLayout = QVBoxLayout()
        gbUrl.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

        self.url = QLineEdit()
        self.url.setPlaceholderText(
            'https://www.nexusmods.com/witcher3/mods/...')
        self.url.setText(url)
        self.url.textChanged.connect(lambda: self.validateUrl(self.url.text()))
        gbUrlLayout.addWidget(self.url)

        self.urlInfo = QLabel('🌐')
        self.urlInfo.setContentsMargins(4, 4, 4, 4)
        self.urlInfo.setMinimumHeight(36)
        self.urlInfo.setWordWrap(True)
        gbUrlLayout.addWidget(self.urlInfo)

        gbUrl.setLayout(gbUrlLayout)
        mainLayout.addWidget(gbUrl)

        # File selection

        gbFiles = QGroupBox('Mod Files')
        gbFilesLayout = QVBoxLayout()
        gbFiles.setSizePolicy(QSizePolicy.MinimumExpanding,
                              QSizePolicy.MinimumExpanding)

        self.files = QTableWidget(0, 4)
        self.files.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
        self.files.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
        self.files.setContextMenuPolicy(Qt.CustomContextMenu)
        self.files.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.files.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.files.setWordWrap(False)
        self.files.setSortingEnabled(True)
        self.files.setFocusPolicy(Qt.StrongFocus)
        self.files.verticalHeader().hide()
        self.files.setSortingEnabled(True)
        self.files.sortByColumn(2, Qt.DescendingOrder)
        self.files.verticalHeader().setVisible(False)
        self.files.verticalHeader().setDefaultSectionSize(25)
        self.files.horizontalHeader().setHighlightSections(False)
        self.files.horizontalHeader().setStretchLastSection(True)
        self.files.setHorizontalHeaderLabels(
            ['File Name', 'Version', 'Upload Date', 'Description'])
        self.files.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.files.verticalScrollBar().valueChanged.connect(
            lambda: self.files.clearFocus())
        self.files.itemSelectionChanged.connect(lambda: self.validateFiles())
        self.files.setDisabled(True)
        self.files.setStyleSheet('''
            QTableView {
                gridline-color: rgba(255,255,255,1);
            }
            QTableView::item {
                padding: 5px;
                margin: 1px 0;
            }
            QTableView::item:!selected:hover {
                background-color: rgb(217, 235, 249);
                padding: 0;
            }
            ''')
        gbFilesLayout.addWidget(self.files)

        _mouseMoveEvent = self.files.mouseMoveEvent
        self.files.hoverIndexRow = -1

        def mouseMoveEvent(event: QMouseEvent) -> None:
            self.files.hoverIndexRow = self.files.indexAt(event.pos()).row()
            _mouseMoveEvent(event)

        self.files.mouseMoveEvent = mouseMoveEvent  # type: ignore
        self.files.setItemDelegate(ModListItemDelegate(self.files))
        self.files.setMouseTracking(True)

        gbFiles.setLayout(gbFilesLayout)
        mainLayout.addWidget(gbFiles)

        # Actions

        actionsLayout = QHBoxLayout()
        actionsLayout.setAlignment(Qt.AlignRight)
        self.download = QPushButton('Download', self)
        self.download.clicked.connect(lambda: self.downloadEvent())
        self.download.setAutoDefault(True)
        self.download.setDefault(True)
        self.download.setDisabled(True)
        actionsLayout.addWidget(self.download)
        cancel = QPushButton('Cancel', self)
        cancel.clicked.connect(self.cancelEvent)
        actionsLayout.addWidget(cancel)
        mainLayout.addLayout(actionsLayout)

        # Setup

        self.setMinimumSize(QSize(420, 420))
        self.setSizePolicy(QSizePolicy.MinimumExpanding,
                           QSizePolicy.MinimumExpanding)
        self.resize(QSize(720, 420))

        self.finished.connect(
            lambda: self.validateUrl.cancel())  # type: ignore
        self.finished.connect(
            lambda: self.downloadEvent.cancel())  # type: ignore

        self.modId = 0
        self.validateUrl(self.url.text())
Exemple #18
0
class Window(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        # Title and dimensions
        self.setWindowTitle("Patterns detection")
        self.setGeometry(0, 0, 800, 500)

        # Main menu bar
        self.menu = self.menuBar()
        self.menu_file = self.menu.addMenu("File")
        exit = QAction("Exit", self, triggered=qApp.quit)
        self.menu_file.addAction(exit)

        self.menu_about = self.menu.addMenu("&About")
        about = QAction("About Qt", self, shortcut=QKeySequence(QKeySequence.HelpContents),
                        triggered=qApp.aboutQt)
        self.menu_about.addAction(about)

        # Create a label for the display camera
        self.label = QLabel(self)
        self.label.setFixedSize(640, 480)

        # Thread in charge of updating the image
        self.th = Thread(self)
        self.th.finished.connect(self.close)
        self.th.updateFrame.connect(self.setImage)

        # Model group
        self.group_model = QGroupBox("Trained model")
        self.group_model.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        model_layout = QHBoxLayout()

        self.combobox = QComboBox()
        for xml_file in os.listdir(cv2.data.haarcascades):
            if xml_file.endswith(".xml"):
                self.combobox.addItem(xml_file)

        model_layout.addWidget(QLabel("File:"), 10)
        model_layout.addWidget(self.combobox, 90)
        self.group_model.setLayout(model_layout)

        # Buttons layout
        buttons_layout = QHBoxLayout()
        self.button1 = QPushButton("Start")
        self.button2 = QPushButton("Stop/Close")
        self.button1.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        self.button2.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        buttons_layout.addWidget(self.button2)
        buttons_layout.addWidget(self.button1)

        right_layout = QHBoxLayout()
        right_layout.addWidget(self.group_model, 1)
        right_layout.addLayout(buttons_layout, 1)

        # Main layout
        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addLayout(right_layout)

        # Central widget
        widget = QWidget(self)
        widget.setLayout(layout)
        self.setCentralWidget(widget)

        # Connections
        self.button1.clicked.connect(self.start)
        self.button2.clicked.connect(self.kill_thread)
        self.button2.setEnabled(False)
        self.combobox.currentTextChanged.connect(self.set_model)

    @Slot()
    def set_model(self, text):
        self.th.set_file(text)

    @Slot()
    def kill_thread(self):
        print("Finishing...")
        self.button2.setEnabled(False)
        self.button1.setEnabled(True)
        self.th.cap.release()
        cv2.destroyAllWindows()
        self.status = False
        self.th.terminate()
        # Give time for the thread to finish
        time.sleep(1)

    @Slot()
    def start(self):
        print("Starting...")
        self.button2.setEnabled(True)
        self.button1.setEnabled(False)
        self.th.set_file(self.combobox.currentText())
        self.th.start()

    @Slot(QImage)
    def setImage(self, image):
        self.label.setPixmap(QPixmap.fromImage(image))
class IngestWindow(QDialog):
    """Subwindow dedicated to data ingest functions.

    Instance attributes:
        - config: Config object holding configuration information
        including API keys.
    """
    config: Config

    # Private Instance Attributes:
    # - _main_layout: Main grid layout
    # - _button_box: Button box holding main control buttons.
    # - _options_group_box: Group box holding most UI widgets
    # - _view: QTableView holding the pandas table viewer.
    # - _pool: QThreadPool for handeling multithreaded functions.
    # - _txt_var: Dictionary holding line edit widgets.
    # - _lists: Dictionary holding the dataset list widget and search type combo widget.
    _main_layout: QGridLayout
    _button_box: QDialogButtonBox
    _options_group_box: QGroupBox
    _view: QTableView
    _pool: QThreadPool
    _delete_btn: QDialogButtonBox
    _txt_var: dict[str, QLineEdit] = {}
    _lists: dict[str, Union[QListWidget, QComboBox]] = {}

    def __init__(self, config: Config) -> None:
        super().__init__()

        self._pool = QThreadPool.globalInstance()

        self._view = QTableView()
        self._view.horizontalHeader().setCascadingSectionResizes(True)
        self._view.horizontalHeader().setStretchLastSection(True)
        self._view.setAlternatingRowColors(True)
        self._view.setSelectionBehavior(QTableView.SelectRows)

        self.config = config

        self._init_options_group_box()
        self._init_button_box()

        main_layout = QGridLayout()
        main_layout.addWidget(self._options_group_box, 0, 0)
        main_layout.addWidget(self._button_box, 1, 0)
        main_layout.addWidget(self._view, 2, 0)
        main_layout.setSizeConstraint(QLayout.SetMinimumSize)

        self._main_layout = main_layout
        self.setLayout(self._main_layout)
        self._type_changed()

        self.setWindowTitle('Train Model')

    def show(self) -> None:
        """Override of QWidget's show() function.

        Refreshes window and then shows the window.
        """
        super().show()
        self._refresh_lists()
        self._refresh_pandas()

    def _init_button_box(self) -> None:
        """Creates the lower control buttons at the bottom of the window."""
        self._button_box = QDialogButtonBox()

        ingest_btn = self._button_box.addButton('Get Data',
                                                QDialogButtonBox.ActionRole)
        self._delete_btn = self._button_box.addButton(
            'Delete Dataset', QDialogButtonBox.ActionRole)
        refresh_btn = self._button_box.addButton('Refresh &Options',
                                                 QDialogButtonBox.ActionRole)

        ingest_btn.clicked.connect(self._ingest)
        self._delete_btn.clicked.connect(self._delete)
        refresh_btn.clicked.connect(self._refresh_lists)

    def _init_options_group_box(self) -> None:
        """Creates the group of training options."""
        self._options_group_box = QGroupBox("Options")

        options_layout = QGridLayout()
        left_options = QGridLayout()
        right_options = QGridLayout()

        self._lists['data'] = QListWidget()
        self._lists['data'].setSelectionMode(
            QtWidgets.QAbstractItemView.SingleSelection)
        self._lists['data'].currentTextChanged.connect(self._refresh_pandas)

        self._lists['type'] = QComboBox()
        for dt in IngestTypes:
            self._lists['type'].addItem(dt.value)

        self._refresh_lists()

        self._lists['type'].currentTextChanged.connect(self._type_changed)

        validator = QRegularExpressionValidator(r'^[\w\-. ]+$')
        cat_validator = QRegularExpressionValidator(r'^[0-9]\d*$')

        dataset_label = QLabel("Avaliable Datasets:")
        search_type_label = QLabel("Symbol/Search Type:")
        search_label = QLabel("Symbol/Search Term:")
        name_label = QLabel("Dataset Name:")
        cat_label = QLabel("Trends Category Code:")

        left_options.addWidget(dataset_label, 0, 0)
        left_options.addWidget(self._lists['data'], 1, 0)

        right_options.addWidget(search_type_label, 0, 0)
        right_options.addWidget(self._lists['type'], 1, 0)

        self._txt_var['ds_name'] = QLineEdit()
        self._txt_var['data_search'] = QLineEdit()
        self._txt_var['search_cat'] = QLineEdit()
        self._txt_var['ds_name'].setValidator(validator)
        self._txt_var['data_search'].setValidator(validator)
        self._txt_var['search_cat'].setValidator(cat_validator)

        self._txt_var['search_cat'].setPlaceholderText('0')

        right_options.addWidget(search_label, 2, 0)
        right_options.addWidget(self._txt_var['data_search'], 3, 0)

        right_options.addWidget(name_label, 4, 0)
        right_options.addWidget(self._txt_var['ds_name'], 5, 0)

        right_options.addWidget(cat_label, 6, 0)
        right_options.addWidget(self._txt_var['search_cat'], 7, 0)

        options_layout.addLayout(left_options, 0, 0)
        options_layout.addLayout(right_options, 0, 1)

        options_layout.setColumnStretch(0, 1)

        self._options_group_box.setLayout(options_layout)

    def _refresh_lists(self) -> None:
        """Refreshes avaliable datasets for training."""
        self._lists['data'].clear()

        data_list = data_ingest.get_avaliable_data(search_type='data')

        self._lists['data'].addItems(data_list)

    def _refresh_pandas(self) -> None:
        """Refreshes the pandas table viewer."""
        df = self._lists['data'].currentItem()
        if df is not None:
            df = df.text()
            if df in data_ingest.get_avaliable_data(search_type='data'):
                df = data_ingest.load_data(df)
                model = PandasModel(df)
                self._view.setModel(model)
                self._delete_btn.setEnabled(True)
                return

        self._delete_btn.setEnabled(False)

    def _type_changed(self) -> None:
        """Updates widget based on type combo box change."""
        if self._lists['type'].currentText() == 'Google Trends':
            self._txt_var['ds_name'].setEnabled(False)
            self._txt_var['search_cat'].setEnabled(True)
        else:
            self._txt_var['ds_name'].setEnabled(True)
            self._txt_var['search_cat'].setEnabled(False)

    def _ingest(self) -> None:
        """Ingests the user requested data and saves it accordingly."""
        self.setEnabled(False)
        search_type = self._lists['type'].currentText()
        search_type = IngestTypes.from_str(search_type)

        search_term = self._txt_var['data_search'].text().strip()
        self._txt_var['data_search'].setText(search_term)

        if search_type in {
                IngestTypes.CryptoCurrenciesDaily,
                IngestTypes.TimeSeriesDailyAdjusted
        }:
            try:
                if search_type == IngestTypes.CryptoCurrenciesDaily:
                    data = data_ingest.async_get([
                        data_ingest.get_cc_daily(search_term,
                                                 self.config,
                                                 cache=False)
                    ])[0]
                elif search_type == IngestTypes.TimeSeriesDailyAdjusted:
                    data = data_ingest.async_get([
                        data_ingest.get_ts_daily_adjusted(search_term,
                                                          self.config,
                                                          cache=False)
                    ])[0]
                else:
                    data = None  # Satisfy PyTa even though raise occurs
                    raise NotImplementedError
            except ce.RateLimited:
                self._error_event(
                    'You are being rate limited. Check Alpha Vantage API key or wait.'
                )
                return
            except ce.UnknownAVType:
                self._error_event(
                    f'{search_term} is an invalid symbol for {search_type}')
                return
        elif search_type == IngestTypes.GoogleTrends:
            trends_thread = TrendsThread(search_term,
                                         self._txt_var['search_cat'].text())

            self._pool.start(trends_thread)

            trends_thread.signals.error.connect(self._error_event)

            trends_thread.signals.dataframe_result.connect(self._ingest_save)
            return
        else:
            self._error_event('Invalid search type.')
            return

        self._ingest_save(data)

    def _ingest_save(self, data: pd.DataFrame) -> None:
        """Generates a name and saves the given dataframe.
        Returns None when complete or on error."""
        search_type = self._lists['type'].currentText()
        search_term = self._txt_var['data_search'].text()

        search_type = IngestTypes.from_str(search_type)
        if search_type == IngestTypes.GoogleTrends:
            cat = self._txt_var['search_cat'].text()

            if cat == '':
                cat = '0'
            name = f'{search_term} {cat};{data_ingest.IngestTypes.GoogleTrends.name}'
        else:
            name = self._txt_var['ds_name'].text()
            if name == '':
                name = data_ingest.name_generator(search_term, search_type)
            else:
                name = data_ingest.name_generator(search_term, search_type,
                                                  name)

        current_datasets = data_ingest.get_avaliable_data(search_type='data')

        if name in current_datasets:
            response = self._error_event(f'{name} will be overwritten.',
                                         choice=True)
            if response == QMessageBox.Abort:
                self.setEnabled(True)
                return

        data_ingest.save_data(name, data)

        self._refresh_lists()
        self.setEnabled(True)

    def _delete(self) -> None:
        """Deletes the currently selected dataset."""
        self.setEnabled(False)
        name = self._lists['data'].selectedItems()

        if len(name) != 0:
            name = name[0].text()

            warning = f'Are you sure you want to delete {name}?'

            response = QMessageBox.warning(self, self.tr("Delete Dataset"),
                                           warning, QMessageBox.Yes,
                                           QMessageBox.No)
            if response == QMessageBox.Yes:
                data_ingest.delete_data(name, file_type='data')
                self._refresh_lists()

        self.setEnabled(True)

    def _error_event(
        self,
        error: str,
        choice: bool = False,
        btn: QMessageBox = QMessageBox.Abort
    ) -> Union[QMessageBox.Ignore, QMessageBox.Abort, None]:
        """Displays an error message with the given error."""
        if choice:
            response = QMessageBox.critical(self, self.tr("Error"), error, btn,
                                            QMessageBox.Ignore)
            return response
        else:
            QMessageBox.critical(self, self.tr("Error"), error, QMessageBox.Ok)
            self.setEnabled(True)
            return None
Exemple #20
0
class Pryme2(QWidget):

    notify_request = Signal(str)

    def __init__(self, parent=None):

        super(Pryme2, self).__init__(parent)

        self.timer_instances = (SimpleTimer(), AlarmClock(), PomoTimer())
        self.timer_selection = QComboBox(self)
        for t in self.timer_instances:
            self.timer_selection.addItem(t.name)
        self.timer = self.timer_instances[0]
        self.commitment_textbox = QLineEdit(self)
        self.commitment_textbox.setPlaceholderText(
            'What do you want to commit?')
        self.commitment_textbox.setClearButtonEnabled(True)
        self.commit_done_btn = QPushButton('&Done', self)
        self.start_btn = QPushButton('&Start', self)
        self.abort_btn = QPushButton('&Abort', self)
        self.abort_btn.hide()
        self.pause_btn = QPushButton('&Pause', self)
        self.pause_btn.hide()
        self.resume_btn = QPushButton('&Resume', self)
        self.resume_btn.hide()

        self.tray = QSystemTrayIcon(self)
        self.tray.setIcon(QIcon('pryme-logo.svg'))
        self.tray.show()

        self.set_ui()
        self.set_connection()
        self.show()

    def set_ui(self):
        self.hlayout = QHBoxLayout()
        self.hlayout.addWidget(self.commitment_textbox)
        self.hlayout.addWidget(self.commit_done_btn)
        self.commit_group = QGroupBox('Commitment')
        self.commit_group.setLayout(self.hlayout)

        self.vlayout = QVBoxLayout()
        self.vlayout.addWidget(self.commit_group)
        self.vlayout.addWidget(self.timer_selection)
        self.vlayout.addWidget(self.timer)

        self.bottom_hlayout = QHBoxLayout()
        self.bottom_hlayout.addWidget(self.start_btn)
        self.bottom_hlayout.addWidget(self.abort_btn)
        self.bottom_hlayout.addWidget(self.pause_btn)
        self.bottom_hlayout.addWidget(self.resume_btn)

        self.vlayout.addLayout(self.bottom_hlayout)
        self.setLayout(self.vlayout)

    def set_connection(self):
        self.timer_selection.currentIndexChanged.connect(self.change_timer)
        self.connect_timer()

    def connect_timer(self):
        self.start_btn.clicked.connect(self.timer.start)
        self.abort_btn.clicked.connect(self.timer.abort)
        self.timer.finished.connect(self.notify)
        self.timer.started.connect(self.set_timer_active_ui)
        self.timer.aborted.connect(self.set_timer_deactive_ui)
        self.timer.finished.connect(self.set_timer_deactive_ui)
        if hasattr(self.timer, 'pause'):
            self.pause_btn.clicked.connect(self.timer.pause)
            self.resume_btn.clicked.connect(self.timer.resume)
            self.timer.paused.connect(self.activate_resume_button)

    def disconnect_timer(self):
        self.timer.disconnect(self)
        self.start_btn.disconnect(self.timer)
        self.abort_btn.disconnect(self.timer)
        self.resume_btn.disconnect(self.timer)

    def notify(self):
        title = self.commitment_textbox.text()
        if not title:
            title = 'Time up!'
        message = self.timer.get_notify_message()
        if not message:
            print(message)
            message = 'Time up!'
        self.tray.showMessage(title, message)
        subprocess.Popen(cmd.split())

    def set_ui_enabled(self, enable: bool):
        self.timer_selection.setEnabled(enable)
        self.commitment_textbox.setEnabled(enable)

    def set_timer_active_ui(self):
        self.activate_start_button(False)
        self.set_ui_enabled(False)

    def set_timer_deactive_ui(self):
        self.activate_start_button(True)
        self.set_ui_enabled(True)

    def activate_start_button(self, activate: bool):
        if activate:
            # active start button
            self.start_btn.show()
            self.abort_btn.hide()
            self.pause_btn.hide()
            self.resume_btn.hide()
        else:
            self.abort_btn.show()
            self.start_btn.hide()
            if hasattr(self.timer, 'pause'):
                self.pause_btn.show()
                self.resume_btn.hide()

    def activate_resume_button(self):
        self.pause_btn.hide()
        self.resume_btn.show()

    @Slot(int)
    def change_timer(self, index):
        self.disconnect_timer()
        self.timer.hide()
        self.vlayout.replaceWidget(self.timer, self.timer_instances[index])
        self.timer = self.timer_instances[index]
        self.connect_timer()
        self.timer.show()
Exemple #21
0
class MainWidget(QWidget):
    def __init__(self, parent=None):
        super(MainWidget, self).__init__(parent)
        self.chart = QChart()
        self.series = QBarSeries()

        self.main_layout = QGridLayout()
        self.button_layout = QGridLayout()
        self.font_layout = QFormLayout()

        self.font_size = QDoubleSpinBox()

        self.legend_posx = QDoubleSpinBox()
        self.legend_posy = QDoubleSpinBox()
        self.legend_width = QDoubleSpinBox()
        self.legend_height = QDoubleSpinBox()

        self.detach_legend_button = QPushButton("Toggle attached")
        self.detach_legend_button.clicked.connect(self.toggle_attached)
        self.button_layout.addWidget(self.detach_legend_button, 0, 0)

        self.add_set_button = QPushButton("add barset")
        self.add_set_button.clicked.connect(self.add_barset)
        self.button_layout.addWidget(self.add_set_button, 2, 0)

        self.remove_barset_button = QPushButton("remove barset")
        self.remove_barset_button.clicked.connect(self.remove_barset)
        self.button_layout.addWidget(self.remove_barset_button, 3, 0)

        self.align_button = QPushButton("Align (Bottom)")
        self.align_button.clicked.connect(self.set_legend_alignment)
        self.button_layout.addWidget(self.align_button, 4, 0)

        self.bold_button = QPushButton("Toggle bold")
        self.bold_button.clicked.connect(self.toggle_bold)
        self.button_layout.addWidget(self.bold_button, 8, 0)

        self.italic_button = QPushButton("Toggle italic")
        self.italic_button.clicked.connect(self.toggle_italic)
        self.button_layout.addWidget(self.italic_button, 9, 0)

        self.legend_posx.valueChanged.connect(self.update_legend_layout)
        self.legend_posy.valueChanged.connect(self.update_legend_layout)
        self.legend_width.valueChanged.connect(self.update_legend_layout)
        self.legend_height.valueChanged.connect(self.update_legend_layout)

        legend_layout = QFormLayout()
        legend_layout.addRow("HPos", self.legend_posx)
        legend_layout.addRow("VPos", self.legend_posy)
        legend_layout.addRow("Width", self.legend_width)
        legend_layout.addRow("Height", self.legend_height)

        self.legend_settings = QGroupBox("Detached legend")
        self.legend_settings.setLayout(legend_layout)
        self.button_layout.addWidget(self.legend_settings)
        self.legend_settings.setVisible(False)

        # Create chart view with the chart
        self.chart_view = QChartView(self.chart, self)

        # Create spinbox to modify font size
        self.font_size.setValue(self.chart.legend().font().pointSizeF())
        self.font_size.valueChanged.connect(self.font_size_changed)

        self.font_layout.addRow("Legend font size", self.font_size)

        # Create layout for grid and detached legend
        self.main_layout.addLayout(self.button_layout, 0, 0)
        self.main_layout.addLayout(self.font_layout, 1, 0)
        self.main_layout.addWidget(self.chart_view, 0, 1, 3, 1)
        self.setLayout(self.main_layout)

        self.create_series()

    def create_series(self):
        self.add_barset()
        self.add_barset()
        self.add_barset()
        self.add_barset()

        self.chart.addSeries(self.series)
        self.chart.setTitle("Legend detach example")
        self.chart.createDefaultAxes()

        self.chart.legend().setVisible(True)
        self.chart.legend().setAlignment(Qt.AlignBottom)

        self.chart_view.setRenderHint(QPainter.Antialiasing)

    def show_legend_spinbox(self):
        self.legend_settings.setVisible(True)
        chart_viewrect = self.chart_view.rect()

        self.legend_posx.setMinimum(0)
        self.legend_posx.setMaximum(chart_viewrect.width())
        self.legend_posx.setValue(150)

        self.legend_posy.setMinimum(0)
        self.legend_posy.setMaximum(chart_viewrect.height())
        self.legend_posy.setValue(150)

        self.legend_width.setMinimum(0)
        self.legend_width.setMaximum(chart_viewrect.width())
        self.legend_width.setValue(150)

        self.legend_height.setMinimum(0)
        self.legend_height.setMaximum(chart_viewrect.height())
        self.legend_height.setValue(75)

    def hideLegendSpinbox(self):
        self.legend_settings.setVisible(False)

    def toggle_attached(self):
        legend = self.chart.legend()
        if legend.isAttachedToChart():
            legend.detachFromChart()
            legend.setBackgroundVisible(True)
            legend.setBrush(QBrush(QColor(128, 128, 128, 128)))
            legend.setPen(QPen(QColor(192, 192, 192, 192)))

            self.show_legend_spinbox()
            self.update_legend_layout()
        else:
            legend.attachToChart()
            legend.setBackgroundVisible(False)
            self.hideLegendSpinbox()
        self.update()

    def add_barset(self):
        series_count = self.series.count()
        bar_set = QBarSet(f"set {series_count}")
        delta = series_count * 0.1
        bar_set.append([1 + delta, 2 + delta, 3 + delta, 4 + delta])
        self.series.append(bar_set)

    def remove_barset(self):
        sets = self.series.barSets()
        len_sets = len(sets)
        if len_sets > 0:
            self.series.remove(sets[len_sets - 1])

    def set_legend_alignment(self):
        button = self.sender()
        legend = self.chart.legend()
        alignment = legend.alignment()

        if alignment == Qt.AlignTop:
            legend.setAlignment(Qt.AlignLeft)
            if button:
                button.setText("Align (Left)")
        elif alignment == Qt.AlignLeft:
            legend.setAlignment(Qt.AlignBottom)
            if button:
                button.setText("Align (Bottom)")
        elif alignment == Qt.AlignBottom:
            legend.setAlignment(Qt.AlignRight)
            if button:
                button.setText("Align (Right)")
        else:
            if button:
                button.setText("Align (Top)")
            legend.setAlignment(Qt.AlignTop)

    def toggle_bold(self):
        legend = self.chart.legend()
        font = legend.font()
        font.setBold(not font.bold())
        legend.setFont(font)

    def toggle_italic(self):
        legend = self.chart.legend()
        font = legend.font()
        font.setItalic(not font.italic())
        legend.setFont(font)

    def font_size_changed(self):
        legend = self.chart.legend()
        font = legend.font()
        font_size = self.font_size.value()
        if font_size < 1:
            font_size = 1
        font.setPointSizeF(font_size)
        legend.setFont(font)

    def update_legend_layout(self):
        legend = self.chart.legend()

        rect = QRectF(self.legend_posx.value(), self.legend_posy.value(),
                      self.legend_width.value(), self.legend_height.value())
        legend.setGeometry(rect)

        legend.update()
Exemple #22
0
class App(QWidget):
    def __init__(self):

        #init
        super(App, self).__init__()

        #▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
        #parameters for the resume generation.
        self.params = {
            "White": 1.0,
            "Black": 1.0,
            "Hispanic": 1.0,
            "Asian": 1.0,
            "GenderRatio": 0.5,
            "TestSection": '',
            "TestMode": 2,
            "WorkPath": "",
            "BeginYear": "",
            "EndYear": "",
            "BeginMonth": "",
            "EndMonth": "",
            "BeginYearEdu": "",
            "EndYearEdu": "",
            "BeginMonthEdu": "",
            "EndMonthEdu": ""
        }
        #▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒

        #Dictionaries for UI buttons

        self.testModes = {"Before": 1, "After": 2, "Replace": 3}

        self.testSections = {
            "Address": 1,
            "Education": 2,
            "Work History": 3,
            "Skills": 4
        }
        #▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
        #Window sizing for application
        self.title = "COEHP Resume Generator"
        self.left = 10
        self.top = 10
        self.width = 100
        self.height = 300

        #▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
        #Window is created here
        self.makeUI()

    #▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
    #Function creates window and adds widgets

    def makeUI(self):

        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.createLayout()

        windowLayout = QGridLayout()

        windowLayout.addWidget(self.box0, 1, 1, 1, 1)
        windowLayout.addWidget(self.box4, 0, 0, 1, 1)
        windowLayout.addWidget(self.box6, 1, 0, 1, 1)
        windowLayout.addWidget(self.box7, 0, 1, 1, 1)
        windowLayout.addWidget(self.box5, 3, 0, 1, 2)
        windowLayout.addWidget(self.box8, 2, 0, 1, 2)

        windowLayout.setAlignment(QtCore.Qt.AlignTop)

        self.setLayout(windowLayout)
        self.show()

    #▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
    #All QGroupBoxes for features are added here.
    def createLayout(self):
        self.box0 = QGroupBox("Timeframe")
        self.box4 = QGroupBox("Test Data")
        self.box6 = QGroupBox("Output Directory")
        self.box5 = QGroupBox("")
        self.box7 = QGroupBox("Demographic Settings")
        self.box8 = QGroupBox("Resume Layout")

        #Demographic Settings

        self.wPercent = QTextEdit("0.25")
        self.bPercent = QTextEdit("0.25")
        self.aPercent = QTextEdit("0.25")
        self.hPercent = QTextEdit("0.25")
        self.gPercent = QTextEdit("0.5")
        self.wLabel = QLabel("White %")
        self.bLabel = QLabel("Black %")
        self.aLabel = QLabel("Asian %")
        self.hLabel = QLabel("Hispanic %")
        self.gLabel = QLabel("       Gender Ratio")

        self.wPercent.setFixedSize(100, 30)
        self.bPercent.setFixedSize(100, 30)
        self.aPercent.setFixedSize(100, 30)
        self.hPercent.setFixedSize(100, 30)
        self.gPercent.setFixedSize(100, 30)

        #Resume Layout Settings

        self.testSectionLabel1 = QLabel("Test Location")
        self.testSectionLabel2 = QLabel("Section")
        self.testSectionLabel3 = QLabel("Location of Content")
        self.sectionSelect = QComboBox()
        self.sectionSelect.addItems(
            ["Address", "Education", "Work History", "Skills"])
        self.sectionSelect.setFixedSize(300, 30)

        self.modeSelect = QComboBox()
        self.modeSelect.addItems(["Before", "After", "Replace"])
        self.modeSelect.setFixedSize(300, 30)

        #Academic Year

        #First Semester
        self.monthBegin = QComboBox()
        self.monthBegin.addItems([
            "January", "February", "March", "April", "May", "June", "July",
            "August", "September", "November", "December"
        ])
        self.monthBegin.setFixedSize(100, 30)

        self.yearBeginLabel = QLabel("First Semester")
        self.yearBegin = QComboBox()
        self.yearBegin.setFixedSize(100, 30)

        for year in range(1970, 2050):
            self.yearBegin.addItem(str(year))

        #Last Semester
        self.monthEnd = QComboBox()
        self.monthEnd.addItems([
            "January", "February", "March", "April", "May", "June", "July",
            "August", "September", "November", "December"
        ])
        self.monthEnd.setFixedSize(100, 30)

        self.yearEnd = QComboBox()
        self.yearEndLabel = QLabel("Semester of Graduation")
        for year in range(1970, 2050):
            self.yearEnd.addItem(str(year))
        self.yearEnd.setFixedSize(100, 30)

        #Earliest relevant employment
        self.monthWorkBegin = QComboBox()
        self.monthWorkBegin.addItems([
            "January", "February", "March", "April", "May", "June", "July",
            "August", "September", "November", "December"
        ])
        self.monthBegin.setFixedSize(100, 30)

        self.yearWorkBeginLabel = QLabel(
            "Earliest Possible Date of Employment")
        self.yearWorkBegin = QComboBox()
        self.yearWorkBegin.setFixedSize(100, 30)

        for year in range(1970, 2050):
            self.yearWorkBegin.addItem(str(year))

        #Latest relevant employment
        self.monthWorkEnd = QComboBox()
        self.monthWorkEnd.addItems([
            "January", "February", "March", "April", "May", "June", "July",
            "August", "September", "November", "December"
        ])
        self.monthWorkEnd.setFixedSize(100, 30)

        self.yearWorkEnd = QComboBox()
        self.yearWorkEndLabel = QLabel("Latest Possible Date of Employment")
        for year in range(1970, 2050):
            self.yearWorkEnd.addItem(str(year))
        self.yearWorkEnd.setFixedSize(100, 30)

        currentYear = date.today().year
        index = currentYear - 1970
        self.yearEnd.setCurrentIndex(index)
        self.yearBegin.setCurrentIndex(index)
        self.yearWorkBegin.setCurrentIndex(index)
        self.yearWorkEnd.setCurrentIndex(index)

        #Output Directory
        self.dirLabel = QLabel("Output Directory")
        self.currentDir = QTextEdit()
        self.currentDir.setText("Not Selected")
        self.currentDir.layout()
        self.currentDir.setFixedSize(300, 30)
        self.currentDir.setReadOnly(True)
        self.outputName = QTextEdit()

        self.outputLabel = QLabel("Output Folder Name")
        self.outputName.setText("None written")
        self.outputName.setToolTip(
            "Type in the name of the new Folder you would like to make for your Resume batch. \n Otherwise, this will use the current timestamp."
        )
        self.outputName.setFixedSize(300, 30)
        #Select ouput folder button

        self.outputButton = QPushButton('Select Output Directory')
        self.outputButton.setToolTip(
            "Click here to tell the generator where to put this batch of Resumes when it is finished."
        )
        self.outputButton.clicked.connect(
            lambda: self.openDir(self.currentDir))
        self.currentTest = QTextEdit()
        self.currentTest.setText("SportsCollegeList.csv")

        #Output Directory
        self.workLabel = QLabel("Output Directory")
        self.currentWork = QTextEdit()
        self.currentWork.setText("SportsCollegeList.csv")
        self.currentWork.layout()
        self.currentWork.setFixedSize(300, 30)
        self.currentWork.setReadOnly(True)

        #Select work datafolder button
        self.workButton = QPushButton('Select Work Data (.CSV)')
        self.workButton.setToolTip(
            "Click here to select a source file for the employment information in this Resume Batch."
        )
        self.workButton.clicked.connect(lambda: self.openDir(self.currentWork))

        #Select School Data

        self.workLabel = QLabel("Output Directory")
        self.currentSchool = QTextEdit()
        self.currentSchool.setText("Not Selected")
        self.currentSchool.layout()
        self.currentSchool.setFixedSize(300, 30)
        self.currentSchool.setReadOnly(True)

        #Select work datafolder button
        self.schoolButton = QPushButton('Select Work Data (.CSV)')
        self.schoolButton.clicked.connect(
            lambda: self.openDir(self.currentWork))

        #Select test data

        self.testLabel = QLabel("Output Directory")
        self.currentTest = QTextEdit()
        self.currentTest.setText("SportsCollegeList.csv")
        self.currentTest.layout()
        self.currentTest.setFixedSize(300, 30)
        self.currentTest.setReadOnly(True)
        self.testButton = QPushButton('Select Test Data (.CSV)')
        self.testButton.clicked.connect(lambda: self.openDir(self.currentTest))

        #Generate Resumes button
        self.begin = QPushButton('Generate Resumes')
        self.begin.clicked.connect(
            lambda: self.beginTask(self.currentTest.toPlainText()))

        layout = QGridLayout()
        self.box0.setLayout(layout)
        layout.addWidget(self.yearBeginLabel, 0, 0, 1, 2)
        layout.addWidget(self.monthBegin, 1, 0, 1, 1)
        layout.addWidget(self.yearBegin, 1, 1, 1, 1)
        layout.addWidget(self.yearEndLabel, 2, 0, 1, 2)
        layout.addWidget(self.monthEnd, 3, 0, 1, 1)
        layout.addWidget(self.yearEnd, 3, 1, 1, 1)

        layout.addWidget(self.yearWorkBeginLabel, 4, 0, 1, 2)
        layout.addWidget(self.monthWorkBegin, 5, 0, 1, 1)
        layout.addWidget(self.yearWorkBegin, 5, 1, 1, 1)
        layout.addWidget(self.yearWorkEndLabel, 6, 0, 1, 2)
        layout.addWidget(self.monthWorkEnd, 7, 0, 1, 1)
        layout.addWidget(self.yearWorkEnd, 7, 1, 1, 1)

        layout1 = QGridLayout()
        self.box8.setLayout(layout1)
        layout1.addWidget(self.testSectionLabel1, 0, 0, 1, 1)
        layout1.addWidget(self.testSectionLabel3, 1, 0, 1, 1)
        layout1.addWidget(self.sectionSelect, 0, 1, 1, 1)
        layout1.addWidget(self.modeSelect, 1, 1, 1, 1)

        layout2 = QGridLayout()
        self.box7.setLayout(layout2)
        layout2.addWidget(self.wLabel, 0, 0, 1, 1)
        layout2.addWidget(self.bLabel, 1, 0, 1, 1)
        layout2.addWidget(self.hLabel, 0, 2, 1, 1)
        layout2.addWidget(self.aLabel, 2, 0, 1, 1)
        layout2.addWidget(self.wPercent, 0, 1, 1, 1)
        layout2.addWidget(self.bPercent, 1, 1, 1, 1)
        layout2.addWidget(self.hPercent, 0, 3, 1, 1)
        layout2.addWidget(self.aPercent, 2, 1, 1, 1)
        layout2.addWidget(self.gLabel, 3, 1, 1, 1)
        layout2.addWidget(self.gPercent, 3, 2, 1, 2)

        layout = QGridLayout()
        self.box5.setLayout(layout)
        layout.addWidget(self.begin, 0, 0, 1, 2)

        layout3 = QGridLayout()
        layout3.addWidget(self.testButton, 0, 0, 1, 2)
        layout3.addWidget(self.currentTest, 1, 0, 1, 2)
        self.box4.setLayout(layout3)

        layout4 = QGridLayout()

        layout4.addWidget(self.outputButton, 0, 0, 1, 2)
        layout4.addWidget(self.currentDir, 1, 0, 1, 2)
        layout4.addWidget(self.outputLabel, 2, 0, 1, 2)
        layout4.addWidget(self.outputName, 3, 0, 1, 2)
        self.box6.setLayout(layout4)

    #▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
    #
    def openDir(self, target):
        fileName = QFileDialog()
        filenames = list()
        if fileName.exec_():
            fileNames = fileName.selectedFiles()
            target.setText(fileNames[0])

    #▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
    #
    def beginTask(self, path):
        self.beginGen(path)

    def beginGen(self, path):

        self.params["White"] = self.wPercent.toPlainText()
        self.params["Black"] = self.bPercent.toPlainText()
        self.params["Hispanic"] = self.hPercent.toPlainText()
        self.params["Asian"] = self.aPercent.toPlainText()
        self.params["GenderRatio"] = self.gPercent.toPlainText()
        self.params["TestMode"] = str(self.modeSelect.currentText())
        self.params["TestSection"] = str(self.sectionSelect.currentText())
        self.params["BeginYear"] = str(self.yearWorkBegin.currentText())
        self.params["EndYear"] = str(self.yearWorkEnd.currentText())
        self.params["BeginMonth"] = str(self.monthWorkBegin.currentText())
        self.params["EndMonth"] = str(self.monthWorkEnd.currentText())
        self.params["workPath"] = "work.csv"
        self.params["BeginYearEdu"] = str(self.yearBegin.currentText())
        self.params["EndYearEdu"] = str(self.yearEnd.currentText())
        self.params["BeginMonthEdu"] = str(self.monthBegin.currentText())
        self.params["EndMonthEdu"] = str(self.monthEnd.currentText())

        print(self.params)
        Printer.begin(self.currentDir.toPlainText(), path,
                      self.outputName.toPlainText(), self.params)
Exemple #23
0
        self._stage_t_btn_connect.setDefaultAction(
            self._action_disconnect_stage_controller if self.
            _stage_controller_status.is_connecting else self.
            _action_connect_stage_controller)
        self._lcr_combobox_port.currentTextChanged.connect(
            self._lcrmeter_port_changed)
        self._stage_combobox_port.currentTextChanged.connect(
            self._stage_controller_port_changed)

        # setup layout
        f_layout_lcr = QFormLayout()
        f_layout_lcr.addRow("Port", self._lcr_combobox_port)
        f_layout_lcr.addRow("Baudrate", self._lcr_combobox_baudrate)
        f_layout_lcr.addWidget(self._lcr_t_btn_connect)
        group_lcr = QGroupBox("LCRMeter")
        group_lcr.setLayout(f_layout_lcr)

        f_layout_stage = QFormLayout()
        f_layout_stage.addRow("Port    ", self._stage_combobox_port)
        f_layout_stage.addWidget(self._stage_t_btn_connect)
        group_stage = QGroupBox("Linear Stage")
        group_stage.setLayout(f_layout_stage)

        v_layout = AVBoxLayout(self)
        v_layout.addWidget(group_lcr)
        v_layout.addWidget(group_stage)

        self.setMinimumWidth(500)

    @Slot()  # type: ignore
    def _connect_lcr(self):
Exemple #24
0
class ImportantFilesAndFolders(QDialog):
    def __init__(self, parent) -> None:
        super().__init__()
        self.parent = parent

        self.setWindowTitle("Important files and folders")
        self.setWindowIcon(QtGui.QIcon(str(Path(cfg.ASSETS_DIR, "info.png"))))

        self.add_shortcuts()
        self.grid_layout_creation_1()
        self.grid_layout_creation_2()

        vbox = QVBoxLayout()
        vbox.addWidget(self.group_box_1)
        vbox.addWidget(self.group_box_2)
        self.setLayout(vbox)

        self.btn_saves.setFocus()

        self.show()

    def grid_layout_creation_1(self) -> None:
        self.group_box_1 = QGroupBox("Files")
        row = -1

        d = cfg.PLATFORM_SETTINGS

        # pprint(d)

        layout = QGridLayout()
        row += 1
        layout.addWidget(QLabel(bold("preferences.ini:")), row, 0)
        fname = cfg.PREFERENCES_INI
        layout.addWidget(QLabel(fname), row, 1)
        btn = QPushButton("Open")
        btn.clicked.connect(partial(opener.open_file_with_editor, self, fname))
        layout.addWidget(btn, row, 2)

        row += 1
        layout.addWidget(QLabel(bold("categories.yaml:")), row, 0)
        fname = cfg.categories_file()
        layout.addWidget(QLabel(fname), row, 1)
        btn = QPushButton("Open")
        btn.clicked.connect(partial(opener.open_file_with_editor, self, fname))
        layout.addWidget(btn, row, 2)

        row += 1
        layout.addWidget(QLabel(bold("settings.json:")), row, 0)
        fname = cfg.SETTINGS_FILE
        layout.addWidget(QLabel(fname), row, 1)
        btn = QPushButton("Open")
        btn.clicked.connect(partial(opener.open_file_with_editor, self, fname))
        layout.addWidget(btn, row, 2)

        self.group_box_1.setLayout(layout)

    def grid_layout_creation_2(self) -> None:
        self.group_box_2 = QGroupBox("Folders")
        row = -1

        d = cfg.PLATFORM_SETTINGS

        layout = QGridLayout()
        row += 1
        layout.addWidget(QLabel(bold("application folder:")), row, 0)
        dname = cfg.BASE_DIR
        layout.addWidget(QLabel(dname), row, 1)
        btn = QPushButton("Open")
        btn.clicked.connect(partial(opener.open_folder, dname))
        layout.addWidget(btn, row, 2)

        row += 1
        layout.addWidget(QLabel(bold("user data dir.:")), row, 0)
        dname = d['root_dir']
        layout.addWidget(QLabel(dname), row, 1)
        btn = QPushButton("Open")
        btn.clicked.connect(partial(opener.open_folder, dname))
        layout.addWidget(btn, row, 2)

        row += 1
        layout.addWidget(QLabel(bold("saves dir.:")), row, 0)
        dname = d['saves_dir']
        layout.addWidget(QLabel(dname), row, 1)
        self.btn_saves = QPushButton("Open")
        self.btn_saves.clicked.connect(partial(opener.open_folder, dname))
        layout.addWidget(self.btn_saves, row, 2)

        row += 1
        layout.addWidget(QLabel(bold("wallpapers dir.:")), row, 0)
        dname = d['wallpapers_dir']
        layout.addWidget(QLabel(dname), row, 1)
        btn = QPushButton("Open")
        btn.clicked.connect(partial(opener.open_folder, dname))
        layout.addWidget(btn, row, 2)

        row += 1
        layout.addWidget(QLabel(bold("tmp dir.:")), row, 0)
        dname = d['tmp_dir']
        layout.addWidget(QLabel(dname), row, 1)
        btn = QPushButton("Open")
        btn.clicked.connect(partial(opener.open_folder, dname))
        layout.addWidget(btn, row, 2)

        row += 1
        layout.addWidget(QLabel(bold("cache dir.:")), row, 0)
        dname = d['cache_dir']
        layout.addWidget(QLabel(dname), row, 1)
        btn = QPushButton("Open")
        btn.clicked.connect(partial(opener.open_folder, dname))
        layout.addWidget(btn, row, 2)

        self.group_box_2.setLayout(layout)

    def copy_to_clipboard(self, text: str) -> None:
        cb = QApplication.clipboard()
        cb.setText(text)

    def add_shortcuts(self) -> None:
        self.shortcutCloseQ = QShortcut(QKeySequence("Q"), self)
        self.shortcutCloseQ.activated.connect(self.close)
Exemple #25
0
    def __init__(
        self,
        controller: StageControllerShot702,
        controller_status: DeviceStatus,
        parent: QWidget = None,
    ):
        super().__init__(parent=parent)
        self._controller = controller
        self._controller_status = controller_status
        self._lcd_position = ALabel()
        self._int_slider = IntSlider()
        self._t_btn_up = create_tool_button(
            arrow_type=Qt.UpArrow,
            fixed_height=50,
            fixed_width=50,
            toggled=self.up_stage,
        )
        self._t_btn_down = create_tool_button(
            arrow_type=Qt.DownArrow,
            fixed_height=50,
            fixed_width=50,
            icon_size=QSize(30, 30),
            toggled=self.down_stage,
        )
        self._t_btn_stop = create_tool_button(
            fixed_width=50,
            fixed_height=50,
            icon=create_qicon(IconNames.STOP_WHITE),
            icon_size=QSize(70, 70),
            toggled=self.stop_stage,
        )
        self._p_button_fix_zero = create_push_button(clicked=self.fix_zero,
                                                     text="Fix Zero")
        self._p_button_move_machine_zero = create_push_button(
            clicked=self.move_to_machine_zero, text="Move Machine Zero-Point")
        self._p_button_set_speed = create_push_button(
            clicked=self.set_stage_speed, fixed_width=100, text="Set")

        # timer
        self.timer_measure_position = create_timer(
            parent=self, timeout=self.measure_position)

        # setup
        self._int_slider.range = 1, 50000
        button_group = QButtonGroup(self)
        button_group.addButton(self._t_btn_up)
        button_group.addButton(self._t_btn_stop)
        button_group.addButton(self._t_btn_down)
        button_group.setExclusive(True)

        # setup layout
        v_layout_control = AVBoxLayout()
        v_layout_control.addWidget(self._t_btn_up)
        v_layout_control.addWidget(self._t_btn_stop)
        v_layout_control.addWidget(self._t_btn_down)
        v_layout_control.setAlignment(Qt.AlignHCenter)
        group_control = QGroupBox("Control")
        group_control.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        group_control.setLayout(v_layout_control)

        h_layout_position = AHBoxLayout()
        h_layout_position.addWidget(add_unit(self._lcd_position, "μm"))
        group_position = QGroupBox("Current Position")
        group_position.setLayout(h_layout_position)

        v_layout_origin = AVBoxLayout()
        v_layout_origin.addWidget(self._p_button_fix_zero)
        v_layout_origin.addWidget(self._p_button_move_machine_zero)
        group_origin = QGroupBox("Origin")
        group_origin.setLayout(v_layout_origin)

        v_layout_speed = AVBoxLayout()
        v_layout_speed.addWidget(add_unit(self._int_slider, "μm/msec"))
        v_layout_speed.addWidget(self._p_button_set_speed,
                                 alignment=Qt.AlignRight)
        group_speed = QGroupBox("Speed Setting")
        group_speed.setLayout(v_layout_speed)

        g_layout = QGridLayout()
        g_layout.addWidget(group_control, 1, 1, 2, 1)
        g_layout.addWidget(group_position, 1, 2)
        g_layout.addWidget(group_origin, 2, 2)
        g_layout.addWidget(group_speed, 3, 1, 1, 2)
        self.setLayout(g_layout)
Exemple #26
0
class ImageInfo(QDialog):
    def __init__(self, parent, img) -> None:
        super().__init__()
        self.parent = parent
        self.commit = self.parent.commit
        self.img = img

        self.setModal(True)  # not sure if it should be modal or not
        # self.parent.setEnabled(False)
        self.setWindowTitle("Image info")
        self.setWindowIcon(QtGui.QIcon(str(Path(cfg.ASSETS_DIR, "info.png"))))

        self.add_shortcuts()
        self.grid_layout_creation_1()
        self.grid_layout_creation_2()

        vbox = QVBoxLayout()
        vbox.addWidget(self.group_box_1)
        vbox.addWidget(self.group_box_2)
        self.setLayout(vbox)

        self.show()

    # def closeEvent(self, event):
    #     self.parent.setEnabled(True)

    def grid_layout_creation_1(self) -> None:
        self.group_box_1 = QGroupBox("Image info")

        layout = QGridLayout()
        layout.addWidget(QLabel(bold("Local file?")), 0, 0)
        layout.addWidget(QLabel("Yes" if self.img.local_file else "No"), 0, 1)

        layout.addWidget(QLabel(bold("Path:")), 1, 0)
        text = self.img.get_absolute_path_or_url()
        layout.addWidget(QLabel(text), 1, 1)
        icon = QtGui.QIcon(str(Path(cfg.ASSETS_DIR, "clipboard.png")))
        btn = QPushButton()
        btn.setIcon(icon)
        btn.setIconSize(QtCore.QSize(ICON_SIZE, ICON_SIZE))
        btn.setToolTip("copy to clipboard")
        btn.clicked.connect(partial(self.copy_to_clipboard, text))
        layout.addWidget(btn, 1, 2)

        layout.addWidget(QLabel(bold("Resolution:")), 2, 0)
        text = "{w} x {h} pixels".format(w=self.img.original_img.width(),
                                         h=self.img.original_img.height())
        layout.addWidget(QLabel(text), 2, 1)

        layout.addWidget(QLabel(bold("Size:")), 3, 0)
        file_size_hr = self.img.get_file_size(human_readable=True)
        text = "{0} ({1} bytes)".format(
            file_size_hr, helper.pretty_num(self.img.get_file_size()))
        layout.addWidget(QLabel(text), 3, 1)

        layout.addWidget(QLabel(bold("Flags:")), 4, 0)
        text = self.img.get_flags()
        layout.addWidget(QLabel(text), 4, 1)

        self.group_box_1.setLayout(layout)

    def grid_layout_creation_2(self) -> None:
        self.group_box_2 = QGroupBox("Summary")

        length = len(self.parent.imgList.get_list_of_images())

        layout = QGridLayout()
        layout.addWidget(QLabel(bold("Marked to be saved:")), 0, 0)
        num = self.commit.to_save()
        text = f"{num} (out of {length})"
        layout.addWidget(QLabel(text), 0, 1)

        layout.addWidget(QLabel(bold("Marked to be deleted:")), 1, 0)
        num = self.commit.to_delete()
        remain = len(self.parent.imgList.get_list_of_images()) - num
        text = f"{num} (out of {length}) [remain {remain}]"
        layout.addWidget(QLabel(text), 1, 1)

        layout.addWidget(QLabel(bold("Marked to save as wallpaper:")), 2, 0)
        num = self.commit.to_wallpaper()
        text = f"{num} (out of {length})"
        layout.addWidget(QLabel(text), 2, 1)

        self.group_box_2.setLayout(layout)

    def copy_to_clipboard(self, text: str) -> None:
        cb = QApplication.clipboard()
        cb.setText(text)

    def add_shortcuts(self) -> None:
        self.shortcutCloseI = QShortcut(QKeySequence("I"), self)
        self.shortcutCloseI.activated.connect(self.close)

        self.shortcutCloseQ = QShortcut(QKeySequence("Q"), self)
        self.shortcutCloseQ.activated.connect(self.close)
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()

        self.proxyModel = QSortFilterProxyModel()
        self.proxyModel.setDynamicSortFilter(True)

        self.sourceGroupBox = QGroupBox("Original Model")
        self.proxyGroupBox = QGroupBox("Sorted/Filtered Model")

        self.sourceView = QTreeView()
        self.sourceView.setRootIsDecorated(False)
        self.sourceView.setAlternatingRowColors(True)

        self.proxyView = QTreeView()
        self.proxyView.setRootIsDecorated(False)
        self.proxyView.setAlternatingRowColors(True)
        self.proxyView.setModel(self.proxyModel)
        self.proxyView.setSortingEnabled(True)

        self.sortCaseSensitivityCheckBox = QCheckBox("Case sensitive sorting")
        self.filterCaseSensitivityCheckBox = QCheckBox("Case sensitive filter")

        self.filterPatternLineEdit = QLineEdit()
        self.filterPatternLineEdit.setClearButtonEnabled(True)
        self.filterPatternLabel = QLabel("&Filter pattern:")
        self.filterPatternLabel.setBuddy(self.filterPatternLineEdit)

        self.filterSyntaxComboBox = QComboBox()
        self.filterSyntaxComboBox.addItem("Regular expression",
                                          REGULAR_EXPRESSION)
        self.filterSyntaxComboBox.addItem("Wildcard",
                                          WILDCARD)
        self.filterSyntaxComboBox.addItem("Fixed string",
                                          FIXED_STRING)
        self.filterSyntaxLabel = QLabel("Filter &syntax:")
        self.filterSyntaxLabel.setBuddy(self.filterSyntaxComboBox)

        self.filterColumnComboBox = QComboBox()
        self.filterColumnComboBox.addItem("Subject")
        self.filterColumnComboBox.addItem("Sender")
        self.filterColumnComboBox.addItem("Date")
        self.filterColumnLabel = QLabel("Filter &column:")
        self.filterColumnLabel.setBuddy(self.filterColumnComboBox)

        self.filterPatternLineEdit.textChanged.connect(self.filterRegExpChanged)
        self.filterSyntaxComboBox.currentIndexChanged.connect(self.filterRegExpChanged)
        self.filterColumnComboBox.currentIndexChanged.connect(self.filterColumnChanged)
        self.filterCaseSensitivityCheckBox.toggled.connect(self.filterRegExpChanged)
        self.sortCaseSensitivityCheckBox.toggled.connect(self.sortChanged)

        sourceLayout = QHBoxLayout()
        sourceLayout.addWidget(self.sourceView)
        self.sourceGroupBox.setLayout(sourceLayout)

        proxyLayout = QGridLayout()
        proxyLayout.addWidget(self.proxyView, 0, 0, 1, 3)
        proxyLayout.addWidget(self.filterPatternLabel, 1, 0)
        proxyLayout.addWidget(self.filterPatternLineEdit, 1, 1, 1, 2)
        proxyLayout.addWidget(self.filterSyntaxLabel, 2, 0)
        proxyLayout.addWidget(self.filterSyntaxComboBox, 2, 1, 1, 2)
        proxyLayout.addWidget(self.filterColumnLabel, 3, 0)
        proxyLayout.addWidget(self.filterColumnComboBox, 3, 1, 1, 2)
        proxyLayout.addWidget(self.filterCaseSensitivityCheckBox, 4, 0, 1, 2)
        proxyLayout.addWidget(self.sortCaseSensitivityCheckBox, 4, 2)
        self.proxyGroupBox.setLayout(proxyLayout)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.sourceGroupBox)
        mainLayout.addWidget(self.proxyGroupBox)
        self.setLayout(mainLayout)

        self.setWindowTitle("Basic Sort/Filter Model")
        self.resize(500, 450)

        self.proxyView.sortByColumn(1, Qt.AscendingOrder)
        self.filterColumnComboBox.setCurrentIndex(1)

        self.filterPatternLineEdit.setText("Andy|Grace")
        self.filterCaseSensitivityCheckBox.setChecked(True)
        self.sortCaseSensitivityCheckBox.setChecked(True)

    def setSourceModel(self, model):
        self.proxyModel.setSourceModel(model)
        self.sourceView.setModel(model)

    def filterRegExpChanged(self):
        syntax_nr = self.filterSyntaxComboBox.currentData()
        pattern = self.filterPatternLineEdit.text()
        if syntax_nr == WILDCARD:
            pattern = QRegularExpression.wildcardToRegularExpression(pattern)
        elif syntax_nr == FIXED_STRING:
            pattern = QRegularExpression.escape(pattern)

        regExp = QRegularExpression(pattern)
        if not self.filterCaseSensitivityCheckBox.isChecked():
            options = regExp.patternOptions()
            options |= QRegularExpression.CaseInsensitiveOption
            regExp.setPatternOptions(options)
        self.proxyModel.setFilterRegularExpression(regExp)

    def filterColumnChanged(self):
        self.proxyModel.setFilterKeyColumn(self.filterColumnComboBox.currentIndex())

    def sortChanged(self):
        if self.sortCaseSensitivityCheckBox.isChecked():
            caseSensitivity = Qt.CaseSensitive
        else:
            caseSensitivity = Qt.CaseInsensitive

        self.proxyModel.setSortCaseSensitivity(caseSensitivity)
Exemple #28
0
    def __init__(self):
        super().__init__()

        # Declare Widgets
        self.homepage_label = QLabel('Home')
        self.search_label = QLabel('Find an Image!')
        self.srch_box = QLineEdit()  # input field for search
        self.srch_btn = QPushButton("Search")

        # Create U.I. Layout
        mbox = QVBoxLayout()  # Main layout

        vbox = QVBoxLayout()  # Layout for search feature
        vbox.addWidget(self.homepage_label)
        vbox.addWidget(self.search_label)
        vbox.addWidget(self.srch_box)
        vbox.addWidget(self.srch_btn)

        gbox1 = QGroupBox()  # Set group for search feature layout
        gbox1.setLayout(vbox)
        mbox.addWidget(gbox1)

        # Home Images
        images = []
        images = self.getHomepageImages()

        # Create layout for images
        vbox2 = QHBoxLayout()  # horizontal layout

        i = 0
        for img in images:  # iterate through images list
            self.label = QLabel()

            pixmap1 = QPixmap(img)  # set image
            pixmap1 = pixmap1.scaled(300, 300, Qt.KeepAspectRatio)

            self.label.setPixmap(pixmap1)

            temp_vbox = QVBoxLayout()
            temp_vbox.addWidget(self.label)

            gbox2 = QGroupBox()  # group box for current image
            gbox2.setLayout(temp_vbox)
            gbox2.setStyleSheet("background-color: grey")

            vbox2.addWidget(gbox2)
            i += 1

        gbox3 = QGroupBox()  # main group box for images
        gbox3.setLayout(vbox2)
        mbox.addWidget(gbox3)
        self.setLayout(mbox)

        # Styling
        self.setStyleSheet("""
            color: orange;
            font-family: Comfortaa;
            """)
        self.srch_btn.setStyleSheet(":hover { background-color:cyan }")
        gbox1.setStyleSheet("""
            font-size: 18px
            """)

        # Listeners
        self.srch_btn.clicked.connect(self.find_images)
Exemple #29
0
class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.iconGroupBox = QGroupBox()
        self.iconLabel = QLabel()
        self.iconComboBox = QComboBox()
        self.showIconCheckBox = QCheckBox()

        self.messageGroupBox = QGroupBox()
        self.typeLabel = QLabel()
        self.durationLabel = QLabel()
        self.durationWarningLabel = QLabel()
        self.titleLabel = QLabel()
        self.bodyLabel = QLabel()

        self.typeComboBox = QComboBox()
        self.durationSpinBox = QSpinBox()
        self.titleEdit = QLineEdit()
        self.bodyEdit = QTextEdit()
        self.showMessageButton = QPushButton()

        self.minimizeAction = QAction()
        self.maximizeAction = QAction()
        self.restoreAction = QAction()
        self.quitAction = QAction()

        self.trayIcon = QSystemTrayIcon()
        self.trayIconMenu = QMenu()

        self.createIconGroupBox()
        self.createMessageGroupBox()

        self.iconLabel.setMinimumWidth(self.durationLabel.sizeHint().width())

        self.createActions()
        self.createTrayIcon()

        self.showMessageButton.clicked.connect(self.showMessage)
        self.showIconCheckBox.toggled.connect(self.trayIcon.setVisible)
        self.iconComboBox.currentIndexChanged.connect(self.setIcon)
        self.trayIcon.messageClicked.connect(self.messageClicked)
        self.trayIcon.activated.connect(self.iconActivated)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.iconGroupBox)
        self.mainLayout.addWidget(self.messageGroupBox)
        self.setLayout(self.mainLayout)

        self.iconComboBox.setCurrentIndex(1)
        self.trayIcon.show()

        self.setWindowTitle("Systray")
        self.resize(400, 300)

    def setVisible(self, visible):
        self.minimizeAction.setEnabled(visible)
        self.maximizeAction.setEnabled(not self.isMaximized())
        self.restoreAction.setEnabled(self.isMaximized() or not visible)
        super().setVisible(visible)

    def closeEvent(self, event):
        if not event.spontaneous() or not self.isVisible():
            return
        if self.trayIcon.isVisible():
            QMessageBox.information(
                self, "Systray",
                "The program will keep running in the system tray. "
                "To terminate the program, choose <b>Quit</b> in the context "
                "menu of the system tray entry.")
            self.hide()
            event.ignore()

    @Slot(int)
    def setIcon(self, index):
        icon = self.iconComboBox.itemIcon(index)
        self.trayIcon.setIcon(icon)
        self.setWindowIcon(icon)
        self.trayIcon.setToolTip(self.iconComboBox.itemText(index))

    @Slot(str)
    def iconActivated(self, reason):
        if reason == QSystemTrayIcon.Trigger:
            pass
        if reason == QSystemTrayIcon.DoubleClick:
            self.iconComboBox.setCurrentIndex(
                (self.iconComboBox.currentIndex() + 1) %
                self.iconComboBox.count())
        if reason == QSystemTrayIcon.MiddleClick:
            self.showMessage()

    @Slot()
    def showMessage(self):
        self.showIconCheckBox.setChecked(True)
        selectedIcon = self.typeComboBox.itemData(
            self.typeComboBox.currentIndex())
        msgIcon = QSystemTrayIcon.MessageIcon(selectedIcon)

        if selectedIcon == -1:  # custom icon
            icon = QIcon(
                self.iconComboBox.itemIcon(self.iconComboBox.currentIndex()))
            self.trayIcon.showMessage(
                self.titleEdit.text(),
                self.bodyEdit.toPlainText(),
                icon,
                self.durationSpinBox.value() * 1000,
            )
        else:
            self.trayIcon.showMessage(
                self.titleEdit.text(),
                self.bodyEdit.toPlainText(),
                msgIcon,
                self.durationSpinBox.value() * 1000,
            )

    @Slot()
    def messageClicked(self):
        QMessageBox.information(
            None, "Systray", "Sorry, I already gave what help I could.\n"
            "Maybe you should try asking a human?")

    def createIconGroupBox(self):
        self.iconGroupBox = QGroupBox("Tray Icon")

        self.iconLabel = QLabel("Icon:")

        self.iconComboBox = QComboBox()
        self.iconComboBox.addItem(QIcon(":/images/bad.png"), "Bad")
        self.iconComboBox.addItem(QIcon(":/images/heart.png"), "Heart")
        self.iconComboBox.addItem(QIcon(":/images/trash.png"), "Trash")

        self.showIconCheckBox = QCheckBox("Show icon")
        self.showIconCheckBox.setChecked(True)

        iconLayout = QHBoxLayout()
        iconLayout.addWidget(self.iconLabel)
        iconLayout.addWidget(self.iconComboBox)
        iconLayout.addStretch()
        iconLayout.addWidget(self.showIconCheckBox)
        self.iconGroupBox.setLayout(iconLayout)

    def createMessageGroupBox(self):
        self.messageGroupBox = QGroupBox("Balloon Message")

        self.typeLabel = QLabel("Type:")

        self.typeComboBox = QComboBox()
        self.typeComboBox.addItem("None", QSystemTrayIcon.NoIcon)
        self.typeComboBox.addItem(
            self.style().standardIcon(QStyle.SP_MessageBoxInformation),
            "Information",
            QSystemTrayIcon.Information,
        )
        self.typeComboBox.addItem(
            self.style().standardIcon(QStyle.SP_MessageBoxWarning),
            "Warning",
            QSystemTrayIcon.Warning,
        )
        self.typeComboBox.addItem(
            self.style().standardIcon(QStyle.SP_MessageBoxCritical),
            "Critical",
            QSystemTrayIcon.Critical,
        )
        self.typeComboBox.addItem(QIcon(), "Custom icon", -1)
        self.typeComboBox.setCurrentIndex(1)

        self.durationLabel = QLabel("Duration:")

        self.durationSpinBox = QSpinBox()
        self.durationSpinBox.setRange(5, 60)
        self.durationSpinBox.setSuffix(" s")
        self.durationSpinBox.setValue(15)

        self.durationWarningLabel = QLabel(
            "(some systems might ignore this hint)")
        self.durationWarningLabel.setIndent(10)

        self.titleLabel = QLabel("Title:")
        self.titleEdit = QLineEdit("Cannot connect to network")
        self.bodyLabel = QLabel("Body:")

        self.bodyEdit = QTextEdit()
        self.bodyEdit.setPlainText(
            "Don't believe me. Honestly, I don't have a clue."
            "\nClick this balloon for details.")

        self.showMessageButton = QPushButton("Show Message")
        self.showMessageButton.setDefault(True)

        messageLayout = QGridLayout()
        messageLayout.addWidget(self.typeLabel, 0, 0)
        messageLayout.addWidget(self.typeComboBox, 0, 1, 1, 2)
        messageLayout.addWidget(self.durationLabel, 1, 0)
        messageLayout.addWidget(self.durationSpinBox, 1, 1)
        messageLayout.addWidget(self.durationWarningLabel, 1, 2, 1, 3)
        messageLayout.addWidget(self.titleLabel, 2, 0)
        messageLayout.addWidget(self.titleEdit, 2, 1, 1, 4)
        messageLayout.addWidget(self.bodyLabel, 3, 0)
        messageLayout.addWidget(self.bodyEdit, 3, 1, 2, 4)
        messageLayout.addWidget(self.showMessageButton, 5, 4)
        messageLayout.setColumnStretch(3, 1)
        messageLayout.setRowStretch(4, 1)
        self.messageGroupBox.setLayout(messageLayout)

    def createActions(self):
        self.minimizeAction = QAction("Minimize", self)
        self.minimizeAction.triggered.connect(self.hide)

        self.maximizeAction = QAction("Maximize", self)
        self.maximizeAction.triggered.connect(self.showMaximized)

        self.restoreAction = QAction("Restore", self)
        self.restoreAction.triggered.connect(self.showNormal)

        self.quitAction = QAction("Quit", self)
        self.quitAction.triggered.connect(qApp.quit)

    def createTrayIcon(self):
        self.trayIconMenu = QMenu(self)
        self.trayIconMenu.addAction(self.minimizeAction)
        self.trayIconMenu.addAction(self.maximizeAction)
        self.trayIconMenu.addAction(self.restoreAction)
        self.trayIconMenu.addSeparator()
        self.trayIconMenu.addAction(self.quitAction)

        self.trayIcon = QSystemTrayIcon(self)
        self.trayIcon.setContextMenu(self.trayIconMenu)
Exemple #30
0
class TrainingWindow(QDialog):
    """Subwindow dedicated to random forest training functions."""

    # Private Instance Attributes:
    # - _main_layout: Main grid layout
    # - _button_box: Button box holding main control buttons.
    # - _options_group_box: Group box holding most UI widgets
    # - _pool: QThreadPool for handeling multithreaded functions.
    # - _txt_var: Dictionary holding line edit widgets.
    # - _lists: Dictionary holding the dataset list widget and combo widget
    # for data selection.
    _main_layout: QGridLayout
    _button_box: QDialogButtonBox
    _options_group_box: QGroupBox
    _pool: QThreadPool
    _txt_var: dict[str, QLineEdit] = {}
    _lists: dict[str, Union[QListWidget, QComboBox]] = {}

    def __init__(self) -> None:
        super().__init__()

        self._pool = QThreadPool.globalInstance()

        self._init_options_group_box()
        self._init_button_box()

        main_layout = QGridLayout()
        main_layout.addWidget(self._options_group_box, 0, 0)
        main_layout.addWidget(self._button_box, 1, 0)
        main_layout.setSizeConstraint(QLayout.SetMinimumSize)

        self._main_layout = main_layout
        self.setLayout(self._main_layout)

        self.setWindowTitle('Train Model')

    def show(self) -> None:
        """Override of QWidget's show() function.

        Refreshes window and then shows the window.
        """
        self._refresh_lists()
        return super().show()

    def _init_button_box(self) -> None:
        """Creates the lower control buttons at the bottom of the window."""
        self._button_box = QDialogButtonBox()

        train_btn = self._button_box.addButton('Train &Model',
                                               QDialogButtonBox.ActionRole)
        refresh_btn = self._button_box.addButton('Refresh &Options',
                                                 QDialogButtonBox.ActionRole)

        train_btn.clicked.connect(self._train_model)
        refresh_btn.clicked.connect(self._refresh_lists)

    def _init_options_group_box(self) -> None:
        """Creates the group of training options."""
        self._options_group_box = QGroupBox("Options")

        options_layout = QGridLayout()
        left_options = QGridLayout()
        right_options = QGridLayout()

        self._lists['data'] = QListWidget()
        self._lists['data'].setSelectionMode(
            QtWidgets.QAbstractItemView.ExtendedSelection)

        self._lists['target'] = QComboBox()
        self._lists['f_target'] = QComboBox()

        self._lists['target'].currentTextChanged.connect(
            self._refresh_f_target_list)

        self._refresh_lists()

        dataset_label = QLabel("Datasets:")
        targets_label = QLabel("Targets:")
        f_target_label = QLabel("Target Feature:")

        left_options.addWidget(dataset_label, 0, 0)
        left_options.addWidget(self._lists['data'], 1, 0)

        right_options.addWidget(targets_label, 0, 0)
        right_options.addWidget(self._lists['target'], 1, 0)
        right_options.addWidget(f_target_label, 2, 0)
        right_options.addWidget(self._lists['f_target'], 3, 0)

        right_options.addLayout(self._init_num_options_group_box(), 4, 0)

        name_validator = QRegularExpressionValidator(r'^[\w\-. ]+$')
        name_label = QLabel("Model Name:")
        self._txt_var['model_name'] = QLineEdit()
        self._txt_var['model_name'].setValidator(name_validator)
        right_options.addWidget(name_label, 5, 0)
        right_options.addWidget(self._txt_var['model_name'], 6, 0)

        options_layout.addLayout(left_options, 0, 0)
        options_layout.addLayout(right_options, 0, 1)

        options_layout.setColumnStretch(0, 1)

        self._options_group_box.setLayout(options_layout)

    def _init_num_options_group_box(self) -> QGridLayout:
        """Returns input layout for inputs involving numbers."""
        num_options_layout = QGridLayout()
        validator = QRegularExpressionValidator(r'^[1-9]\d*$')

        window_size_label = QLabel("Window Size:")
        target_shift_label = QLabel("Target Shift:")
        n_trees_label = QLabel("Trees in Forest:")
        max_depth_label = QLabel("Tree Max Depth:")
        sample_sz_label = QLabel("Sample Size:")
        seed_label = QLabel("Seed:")

        self._txt_var['window_size'] = QLineEdit()
        self._txt_var['target_shift'] = QLineEdit()
        self._txt_var['n_trees'] = QLineEdit('10')
        self._txt_var['max_depth'] = QLineEdit('10')
        self._txt_var['sample_sz'] = QLineEdit('300')
        self._txt_var['seed'] = QLineEdit('12')

        for dataset in self._txt_var.values():
            dataset.setValidator(validator)

        num_options_layout.addWidget(window_size_label, 0, 0)
        num_options_layout.addWidget(self._txt_var['window_size'], 1, 0)

        num_options_layout.addWidget(target_shift_label, 0, 1)
        num_options_layout.addWidget(self._txt_var['target_shift'], 1, 1)

        num_options_layout.addWidget(n_trees_label, 2, 0)
        num_options_layout.addWidget(self._txt_var['n_trees'], 3, 0)

        num_options_layout.addWidget(max_depth_label, 2, 1)
        num_options_layout.addWidget(self._txt_var['max_depth'], 3, 1)

        num_options_layout.addWidget(sample_sz_label, 4, 0)
        num_options_layout.addWidget(self._txt_var['sample_sz'], 5, 0)

        num_options_layout.addWidget(seed_label, 4, 1)
        num_options_layout.addWidget(self._txt_var['seed'], 5, 1)

        return num_options_layout

    def _refresh_lists(self) -> None:
        """Refreshes avaliable datasets for training."""
        self._lists['data'].clear()
        self._lists['target'].clear()

        data_list = data_ingest.get_avaliable_data(search_type='data')

        self._lists['data'].addItems(data_list)
        self._lists['target'].addItems(data_list)

    def _refresh_f_target_list(self) -> None:
        """Refreshes avaliable features for the selected target."""
        dataset = self._lists['target'].currentText()
        self._lists['f_target'].clear()
        if dataset != '':
            try:
                features = data_ingest.load_data(dataset).columns
                self._lists['f_target'].addItems(features)
            except:
                self._error_event(f'{dataset} is an invalid dataset.')
                raise

    def _train_model(self) -> None:
        """Trains a model and saves it based on current params."""
        self.setEnabled(False)
        for x in self._txt_var.items():
            if x[1].text() == '':
                self._error_event(f'{x[0]} is a required input.')
                return None

        dataframes = self._lists['data'].selectedItems()

        if len(dataframes) == 0:
            self._error_event('Datasets are a required input.')
            return None

        dfs = []
        for x in dataframes:
            try:
                dfs.append(data_ingest.load_data(x.text()))
            except:
                response = self._error_event(
                    f'{x.text()} is an invalid dataset.', choice=True)
                if response == QtWidgets.QMessageBox.Abort:
                    return None
                raise
        target_name = self._lists['target'].currentText()
        try:
            target = data_ingest.load_data(target_name)
            if len(target.columns) > 1:
                target = pd.DataFrame(
                    target[self._lists['f_target'].currentText()])
        except:
            response = self._error_event(
                f'{target_name} is an invalid dataset.', choice=True)
            if response == QtWidgets.QMessageBox.Abort:
                return None
            raise

        req_features = {
            sym.text().split(';', maxsplit=1)[0]
            for sym in dataframes
        }

        window_args = WindowArgs(int(self._txt_var['window_size'].text()),
                                 int(self._txt_var['target_shift'].text()),
                                 req_features, dfs, target,
                                 self._lists['f_target'].currentText())
        forest_args = ForestArgs(int(self._txt_var['n_trees'].text()),
                                 int(self._txt_var['sample_sz'].text()),
                                 max_depth=int(
                                     self._txt_var['max_depth'].text()),
                                 seed=int(self._txt_var['seed'].text()))

        current_models = data_ingest.get_avaliable_data(search_type='model')

        name = self._txt_var['model_name'].text()

        if name in current_models:
            response = self._error_event(f'{name} will be overwritten.',
                                         choice=True)
            if response == QMessageBox.Abort:
                self.setEnabled(True)
                return None

        training = TrainingThread(window_args, forest_args, name)

        self._pool.start(training)

        training.signals.float_result.connect(self._training_complete_event)

        return None

    def _training_complete_event(self, return_value: float) -> None:
        """Display information about completed model training."""
        QMessageBox.information(
            self, self.tr("Information"),
            f'Model created and saved with final R-Squared of: {return_value}',
            QtWidgets.QMessageBox.Ok)
        self.setEnabled(True)

    def _error_event(
        self,
        error: str,
        choice: bool = False
    ) -> Union[QtWidgets.QMessageBox.Ignore, QtWidgets.QMessageBox.Abort,
               None]:
        """Displays an error message with the given error."""
        if choice:
            response = QMessageBox.critical(self, self.tr("Error"), error,
                                            QtWidgets.QMessageBox.Abort,
                                            QtWidgets.QMessageBox.Ignore)
            return response
        else:
            QMessageBox.critical(self, self.tr("Error"), error,
                                 QtWidgets.QMessageBox.Ok)
            self.setEnabled(True)
            return None