class GSideToolbar(QWidget): selectionChanged = pyqtSignal(str) def __init__(self, buttons): super().__init__() self.selectedId = None self.mainLayout = QVBoxLayout(self) self.buttonGroup = QButtonGroup() self.buttons = {} for button in buttons: b = QPushButton(button.name) self.buttonGroup.addButton(b) self.buttonGroup.setId(b, button.id) self.buttons[button.id] = b self.mainLayout.addWidget(b) self.buttonGroup.buttonClicked.connect(self.buttonClicked) self.mainLayout.addStretch() def buttonState(self, state): pass def buttonClicked(self, button: QPushButton): buttonId = self.buttonGroup.id(button) buttonName = self.buttons[buttonId].text() self.selectionChanged.emit(buttonName) @staticmethod def createButton(text, icon): pass
class RadioButtonWidget(QWidget): def __init__(self, label, instruction, button_list): super().__init__() self.title_label = QLabel(label) self.radio_group_box = QGroupBox(instruction) self.radio_button_list = [] for button in button_list: self.radio_button_list.append(QRadioButton(button)) self.radio_button_list[0].setChecked(True) self.radio_button_layout = QVBoxLayout() self.radio_button_group = QButtonGroup() for index, button in enumerate(self.radio_button_list, start=1): self.radio_button_layout.addWidget(button) self.radio_button_group.addButton(button) self.radio_button_group.setId(button, index) self.radio_group_box.setLayout(self.radio_button_layout) self.main_layout = QVBoxLayout() self.main_layout.addWidget(self.title_label) self.main_layout.addWidget(self.radio_group_box) self.setLayout(self.main_layout) def selected_button(self): return self.radio_button_group.checkedId()
class GSideToolbar(QWidget): selectionChanged = pyqtSignal(str) def __init__(self, buttons): super().__init__() self.selectedId = None self.mainLayout = QVBoxLayout(self) self.buttonGroup = QButtonGroup() self.buttons = {} for button in buttons: b = QPushButton(button.name) self.buttonGroup.addButton(b) self.buttonGroup.setId(b, button.id) self.buttons[button.id] = b self.mainLayout.addWidget(b) self.buttonGroup.buttonClicked.connect(self.buttonClicked) self.mainLayout.addStretch() def buttonState(self, state): pass def buttonClicked(self, button : QPushButton): buttonId = self.buttonGroup.id(button) buttonName = self.buttons[buttonId].text() self.selectionChanged.emit(buttonName) @staticmethod def createButton(text, icon): pass
class SignChoiceDialog(QDialog): def __init__(self, sign_list): super().__init__() self.result_idx = -1 self.label = QLabel("Choose the sign:") layout = QGridLayout() layout.addWidget(self.label, 0, 0) self.btn_grp = QButtonGroup() self.btn_grp.setExclusive(True) for idx, sign_info in enumerate(sign_list): btn = SignSelectButton(sign_info[0], idx, self) btn.setIcon(QIcon(sign_info[1])) btn.setIconSize(QSize(24, 24)) layout.addWidget(btn, idx + 1, 0) self.btn_grp.addButton(btn) self.btn_grp.setId(btn, idx) self.btn_grp.buttonClicked.connect(self.on_click) self.setLayout(layout) self.show() def on_click(self, btn): self.result_idx = btn.idx self.close() def get_result(self): # -1 - no selection return self.result_idx
def getColorPolygonAndBrushStyle( initial_color: Union[QColor, Qt.GlobalColor, QGradient] = QColor(), initial_polygon: NodePolygon = NodePolygon.Circle, initial_brushstyle: Qt.BrushStyle = Qt.NoBrush, parent: Optional[QWidget] = None, title: str = '', options: Union[QColorDialog.ColorDialogOptions, QColorDialog.ColorDialogOption] = QColorDialog.ColorDialogOptions()) \ -> (QColor, NodePolygon): dlg = QColorDialog(parent) # Add buttons to select polygon polygons_group = QButtonGroup(parent) polygons_layout = QHBoxLayout(parent) for p in NodePolygon: if p == NodePolygon.Custom: continue button = QToolButton(parent) button.setCheckable(True) button.setText(p.name) button.setIcon(QIcon(nodePolygonToPixmap(p, button.iconSize()))) if p == initial_polygon: button.setChecked(True) polygons_group.addButton(button) polygons_group.setId(button, p.value) polygons_layout.addWidget(button) dlg.layout().insertLayout(dlg.layout().count()-1, polygons_layout) # Add buttons to select brush style brushstyle_group = QButtonGroup(parent) brushstyle_layout = QHBoxLayout(parent) for p in NODE_BRUSH_STYLES: button = QToolButton(parent) button.setCheckable(True) button.setIcon(QIcon(nodeBrushStyleToPixmap(p, button.iconSize()))) if p == initial_brushstyle: button.setChecked(True) brushstyle_group.addButton(button) brushstyle_group.setId(button, p) brushstyle_layout.addWidget(button) dlg.layout().insertLayout(dlg.layout().count()-1, brushstyle_layout) if title: dlg.setWindowTitle(title) dlg.setOptions(options) dlg.setCurrentColor(initial_color) dlg.exec_() return (dlg.selectedColor(), NodePolygon(polygons_group.checkedId()), brushstyle_group.checkedId(), )
def initUI(self): bl = QVBoxLayout() widget = QWidget() widget.setLayout(bl) self.setCentralWidget(widget) cb = QCheckBox('Show title', self) cb.stateChanged.connect(self.changeTitle) bl.addWidget(cb) options = ['Czerwony', 'Żółty', 'Zielony'] rb = [QRadioButton(o) for o in options] cbg = QButtonGroup(self) cbg.setExclusive(True) for id, ch in enumerate(options): rb = QRadioButton(ch) cbg.addButton(rb) rb.setChecked(True) cbg.setId(rb, id) bl.addWidget(rb) cbg.buttonClicked.connect(self.nowyKolor) self.lineEdit = QLineEdit('0') objValidator = QIntValidator(self) objValidator.setRange(0, 255) self.lineEdit.setValidator(objValidator) self.lineEdit.textChanged.connect(self.lineEdit_change) self.slider = QSlider(Qt.Horizontal) self.slider.setMaximum(255) self.slider.setMinimum(0) self.slider.valueChanged.connect(self.slider_change) self.rectangle = QLabel() self.rectangle.setGeometry(QRect(0, 550, 150, 31)) bl.addWidget(self.rectangle) bl.addWidget(self.slider) bl.addWidget(self.lineEdit) exitAction = QAction('Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.close) self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(exitAction) toolbar = self.addToolBar('Exit') toolbar.addAction(exitAction) self.setGeometry(300, 300, 350, 250) self.setWindowTitle('Sample') self.show()
class RecordWindow(QDialog): def __init__(self): super().__init__() self.setWindowTitle("Рекорды") self.setFixedSize(400, 300) self.init_ui() def init_ui(self): font = QFont() font.setPointSize(12) self.tableWidget = QTableWidget(self) self.tableWidget.setGeometry(QtCore.QRect(140, 0, 260, 300)) self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) self.tableWidget.setColumnCount(2) self.tableWidget.setRowCount(0) self.buttonGroup = QButtonGroup(self) for n, text in enumerate(['Новичок', 'Эксперт', 'Бывалый']): rb = QRadioButton(self) rb.setGeometry(QtCore.QRect(30, 100 + 30 * n, 91, 17)) rb.setText(text) rb.setFont(font) self.buttonGroup.addButton(rb) self.buttonGroup.setId(rb, n) self.buttonGroup.buttonClicked.connect(self.choose_table) self.tableWidget.setHorizontalHeaderLabels(["Имя", "Время"]) self.tableWidget.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) self.game_stat = GameStat() self.buttonGroup.button(0).click() def choose_table(self): res = self.game_stat.get_records(self.sender().checkedButton().text()) self.tableWidget.setRowCount(len(res)) for i in range(len(res)): name = QTableWidgetItem(res[i]["name"]) name.setTextAlignment(QtCore.Qt.AlignCenter) time = QTableWidgetItem(str(res[i]["time"])) time.setTextAlignment(QtCore.Qt.AlignCenter) self.tableWidget.setItem(i, 0, name) self.tableWidget.setItem(i, 1, time) # self.tableWidget.resizeColumnsToContents() def show(self): self.exec()
def set_engine_option(self, engine_option: List[ConfigParam]): row_count = self._main_layout.rowCount() for i in range(row_count - 1, 1, -1): self._main_layout.removeRow(i) if len(engine_option) == 0: return self._state_engine_option = engine_option self._state_engine_option_holder.clear() for param in engine_option: engine_option_label = QLabel() engine_option_label.setText(param.title) if param.config_type == ConfigType.RADIO: assert isinstance(param, RadioParam) option_group = QButtonGroup() button_layout = QHBoxLayout() for idx, (key, value) in enumerate(param.options.items()): radio_btn = QRadioButton() radio_btn.setText(value) if idx == 0: radio_btn.setChecked(True) radio_btn.clicked.connect(lambda: self.modified.emit()) option_group.addButton(radio_btn) option_group.setId(radio_btn, idx) button_layout.addWidget(radio_btn) self._main_layout.addRow(engine_option_label, button_layout) self._state_engine_option_holder.append(option_group) elif param.config_type == ConfigType.FLOAT: assert isinstance(param, FloatParam) spinbox = QDoubleSpinBox() spinbox.setValue(param.default) spinbox.setMinimum(0) spinbox.setSingleStep(param.step) spinbox.valueChanged.connect(lambda: self.modified.emit()) self._state_engine_option_holder.append(spinbox) self._main_layout.addRow(engine_option_label, spinbox)
class RadioButton(QWidget): def __init__(self, label, button_list): super().__init__() self.title_label = QLabel(label) self.radio_group_box = QGroupBox() self.radio_button_group = QButtonGroup() self.radio_button_list = [] for button in button_list: self.radio_button_list.append(QRadioButton(button)) self.radio_button_list[0].setChecked(True) self.radio_button_layout = QVBoxLayout() counter = 1 for button in self.radio_button_list: self.radio_button_layout.addWidget(button) self.radio_button_group.addButton(button) self.radio_button_group.setId(button, counter) counter += 1 self.radio_group_box.setLayout(self.radio_button_layout) self.main_radio_button_layout = QVBoxLayout() self.main_radio_button_layout.addWidget(self.title_label) self.main_radio_button_layout.addWidget(self.radio_group_box) self.setLayout(self.main_radio_button_layout) def selected_button(self): return self.radio_button_group.checkedId() def check_first(self): self.radio_button_list[0].setChecked(True)
def start_quiz_options(self): # Builds the window that displays when a new quiz begins ### Initial Setup ### difficulty = (50, 100, 250, 500, 1000) questions = (25, 50, 1000) # These tuples hold the what each option below corresponds to # The difficulty is how many words will be chosen for questions # the questions will be how many questions the quiz contains start_quiz_window = QDialog(None, Qt.WindowCloseButtonHint) # Qt.WindowCloseButtonHint Prevents the ? button from appearing # in the dialog window options_layout = QHBoxLayout() # Holds the radio button options for starting a game. ### Difficulty Selection ### start_quiz_layout = QVBoxLayout() set_difficulty_container = QGroupBox('Question Difficulty') set_difficulty_container.setToolTip( 'Choose how many words will be in the question pool.\n' + 'Easy: 50 Most common words used.\n' + 'Normal: 100 Most common words used.\n' + 'Hard: 250 Most common words used.\n' + 'Very Hard: 500 Most common words used.\n' + 'Everything: ALL 1000 words used') start_quiz_layout.addLayout(options_layout) set_difficulty_layout = QVBoxLayout() set_difficulty_group = QButtonGroup() # Groups the difficulty Radio Buttons together self.difficulty_buttons = (QRadioButton('Easy'), QRadioButton('Normal'), QRadioButton('Hard'), QRadioButton('Very Hard'), QRadioButton('Everything')) # Difficulties correspond to how common the words in the questions occur in Latin # Easy: 50 Most Common Words # Normal: 100 Most Common Words # Hard: 250 Most Common Words # Very Hard: 500 Most Common Words # Everything: All 1000(ish) Words id_num = 0 for button in self.difficulty_buttons: # This loop adds all the buttons to the set_difficulty_group, # Gives them an ID number, and adds them to the GroupBox's layout set_difficulty_group.addButton(button) set_difficulty_group.setId(button, id_num) id_num += 1 set_difficulty_layout.addWidget(button) self.difficulty_buttons[0].setChecked(True) # Makes Easy Mode selected by default set_difficulty_container.setLayout(set_difficulty_layout) options_layout.addWidget(set_difficulty_container) ### Number of Questions ### no_of_q_layout = QVBoxLayout() no_of_q_container = QGroupBox('Number of Questions') no_of_q_container.setToolTip( 'Choose the number of questions. If "All" is chosen,\n' + 'each word will have a question!\n' + 'CAUTION: This can make for a long quiz!') no_of_q_group = QButtonGroup() self.no_of_q_buttons = (QRadioButton('25'), QRadioButton('50'), QRadioButton('All')) id_num = 0 for button in self.no_of_q_buttons: no_of_q_group.addButton(button) no_of_q_group.setId(button, id_num) id_num += 1 no_of_q_layout.addWidget(button) self.no_of_q_buttons[0].setChecked(True) no_of_q_container.setLayout(no_of_q_layout) options_layout.addWidget(no_of_q_container) ### Start and Cancel Buttons ### button_layout = QHBoxLayout() start_button = QPushButton('Start') start_button.clicked.connect(start_quiz_window.accept) # When clicked, returns a 1 cancel_button = QPushButton('Cancel') cancel_button.clicked.connect(start_quiz_window.reject) # When clicked returns a 0 button_layout.addStretch(1) button_layout.addWidget(start_button) button_layout.addWidget(cancel_button) start_quiz_layout.addLayout(button_layout) ### Misc Window Settings ### start_quiz_window.setGeometry(400, 400, 150, 150) start_quiz_window.setWindowTitle('Start New Quiz') start_quiz_window.setLayout(start_quiz_layout) choice = start_quiz_window.exec_() # Returns a number corresponding to the user's choice. if choice == 1: return (difficulty[set_difficulty_group.checkedId()], questions[no_of_q_group.checkedId()]) else: return
class MainWindow(QWidget): def __init__(self, inList): super().__init__() self.inList = inList self.nameFrom = 'Folder' self.codec = 'utvideo' self.alpha = False self.frameRate = 24 self.defaulStyle = '' self.okIcon = QIcon(self.style().standardIcon(QStyle.SP_CustomBase)) self.okPix = QPixmap(self.okIcon.pixmap(QSize(13, 13))) self.goodIcon = QIcon(self.style().standardIcon(QStyle.SP_DialogApplyButton)) self.goodPix = QPixmap(self.goodIcon.pixmap(QSize(13, 13))) self.badIcon = QIcon(self.style().standardIcon(QStyle.SP_MessageBoxCritical)) self.badPix = QPixmap(self.badIcon.pixmap(QSize(13, 13))) self.processingIcon = QIcon(self.style().standardIcon(QStyle.SP_ArrowRight)) self.processingPix = QPixmap(self.processingIcon.pixmap(QSize(13, 13))) self.removeIcon = QIcon(self.style().standardIcon(QStyle.SP_DockWidgetCloseButton)) self.removePix = QPixmap(self.removeIcon.pixmap(QSize(19, 19))) self.folderIcon = QIcon(self.style().standardIcon(QStyle.SP_FileDialogNewFolder)) self.folderPix = QPixmap(self.folderIcon.pixmap(QSize(19, 19))) self.pbList = [] self.chList = [] self.lblList = [] self.rmbList = [] #self.newFolders = [] self.initUI() def initUI(self): self.resize(720, 300) self.setWindowTitle('FFMpeg Python Compressor') self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setContentsMargins(11, 11, 11, 11) self.verticalLayout.setSpacing(11) #COMBOBOX LABELS self.gridLayoutControlls = QGridLayout() self.codecLabel = QLabel('Codec', self) self.codecLabel.setMinimumHeight(13) self.alphaLabel = QLabel('Alpha' , self) self.alphaLabel.setMinimumHeight(13) self.frameRateLabel = QLabel('Frame Rate' , self) self.frameRateLabel.setMinimumHeight(13) self.gridLayoutControlls.addWidget(self.codecLabel, 0, 0, 1, 1) self.gridLayoutControlls.addWidget(self.alphaLabel, 0, 1, 1, 1) self.gridLayoutControlls.addWidget(self.frameRateLabel, 0, 2, 1, 1) #COMBOBOXES AND COMPRESS BUTTON self.codecComboBox = QComboBox(self) self.codecComboBox.setMinimumSize(80,23) self.codecComboBox.addItem("UT Video") self.codecComboBox.activated[str].connect(self.chooseCodec) self.alphaComboBox = QComboBox(self) self.alphaComboBox.setMinimumSize(80,23) self.alphaComboBox.addItem("No Alpha") self.alphaComboBox.addItem("with Alpha") self.alphaComboBox.activated[str].connect(self.chooseAlpha) self.frameRateComboBox = QComboBox(self) self.frameRateComboBox.setMinimumSize(80,23) self.frameRateComboBox.addItem("23.976") self.frameRateComboBox.addItem("24.00") self.frameRateComboBox.addItem("29.97") self.frameRateComboBox.addItem("30.00") self.frameRateComboBox.setCurrentIndex(1) self.frameRateComboBox.activated[str].connect(self.chooseFrameRate) self.compressButton = QPushButton('Compress', self) self.compressButton.setMinimumSize(80,23) self.compressButton.clicked[bool].connect(self.compressPress) self.gridLayoutControlls.addWidget(self.codecComboBox, 1, 0, 1, 1) self.gridLayoutControlls.addWidget(self.alphaComboBox, 1, 1, 1, 1) self.gridLayoutControlls.addWidget(self.frameRateComboBox, 1, 2, 1, 1) self.gridLayoutControlls.addWidget(self.compressButton, 1, 3, 1, 1) #RADIO BUTTON GROUP self.groupBox = QButtonGroup(self) self.radio1 = QRadioButton('Output file name from Folder name', self) self.radio1.setMinimumSize(80,25) self.radio2 = QRadioButton('Output file name from File name', self) self.radio2.setMinimumSize(80,25) self.radio1.setChecked(True) self.groupBox.addButton(self.radio1,1) self.groupBox.addButton(self.radio2,2) self.groupBox.buttonClicked[int].connect(self.radioBtnState) self.gridLayoutControlls.addWidget(self.radio1, 2, 0, 1, 2) self.gridLayoutControlls.addWidget(self.radio2, 2, 2, 1, 2) #LINE self.line = QFrame(self) self.line.setLineWidth(2) self.line.setMinimumHeight(3) self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.gridLayoutControlls.addWidget(self.line, 3, 0, 1, 4) #PROGRESS BAR self.gridLayoutProgress = QGridLayout() self.gridLayoutProgress.setVerticalSpacing(11) self.gridLayoutProgress.setHorizontalSpacing(6) self.gridLayoutProgress.setSizeConstraint(QLayout.SetNoConstraint) self.removeGroupBox = QButtonGroup(self) self.addProgressBarUI(self.inList) self.removeGroupBox.buttonClicked[int].connect(self.removeButtonClicked) #ADD MORE AREA self.gridLayoutAddMore = QGridLayout() self.gridLayoutAddMore.setContentsMargins(0, 0, 0, 0) self.dragAndDropLabel_1 = QLabel("Drag and Drop folders here", self) self.dragAndDropLabel_1.setMinimumSize(QSize(120, 40)) self.dragAndDropLabel_1.setAlignment(Qt.AlignCenter) self.dragAndDropLabel_2 = QLabel("", self) self.dragAndDropLabel_2.setFixedSize(QSize(20, 40)) self.dragAndDropLabel_2.setAlignment(Qt.AlignCenter) self.dragAndDropLabel_2.setPixmap(self.folderPix) sI = QSpacerItem(40, 40,QSizePolicy.Expanding, QSizePolicy.Minimum) sI2 = QSpacerItem(40, 40,QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayoutAddMore.addItem(sI, 1, 0, 1, 1) self.gridLayoutAddMore.addWidget(self.dragAndDropLabel_2, 1, 1, 1, 1) self.gridLayoutAddMore.addWidget(self.dragAndDropLabel_1, 1, 2, 1, 1) self.gridLayoutAddMore.addItem(sI2, 1, 3, 1, 1) #DEBUG AREA self.gridLayoutDebug = QGridLayout() self.line_2 = QFrame(self) self.line_2.setLineWidth(2) self.line_2.setFrameShape(QFrame.HLine) self.line_2.setFrameShadow(QFrame.Sunken) self.exploreOutputBtn = QPushButton('Explore Output',self) self.exploreOutputBtn.clicked[bool].connect(self.exploreOutput) self.hideShowLog = QPushButton('Show Log',self) self.hideShowLog.setCheckable(True) self.hideShowLog.clicked[bool].connect(self.showDebugLog) #self.hideShowLog.setMinimumSize(QSize(0, 20)) self.logText = QPlainTextEdit('',self) self.logText.setReadOnly(True) self.logText.hide() self.spacerItem = QSpacerItem(20, 0, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridLayoutDebug.addWidget(self.line_2, 0, 0, 1, 1) self.gridLayoutDebug.addWidget(self.exploreOutputBtn, 1, 0, 1, 1) self.gridLayoutDebug.addWidget(self.hideShowLog, 2, 0, 1, 1) self.gridLayoutDebug.addWidget(self.logText, 3, 0, 1, 1) self.gridLayoutDebug.addItem(self.spacerItem, 4, 0, 1, 1) self.verticalLayout.addLayout(self.gridLayoutControlls) self.verticalLayout.addLayout(self.gridLayoutProgress) self.verticalLayout.addLayout(self.gridLayoutAddMore) self.verticalLayout.addLayout(self.gridLayoutDebug) # Enable dragging and dropping onto the GUI self.setAcceptDrops(True) #QtCore.QMetaObject.connectSlotsByName(self) self.show() self.setMinimumSize(self.size()) self.threadpool = QThreadPool() self.threadpool.setMaxThreadCount(1) print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount()) ''' Progress bar populate function ''' def addProgressBarUI(self, arr): pbCount = len(self.pbList) for i in range(len(arr)): tempCheckBox = QCheckBox(self) tempCheckBox.setChecked(True) tempCheckBox.setMinimumSize(14,21) tempRemoveButton = QPushButton(self) tempRemoveButton.setIcon(self.removeIcon) tempRemoveButton.setFlat(True) tempRemoveButton.setIconSize(QSize(19,19)) tempRemoveButton.setFixedSize(QSize(19,21)) tempPB = QProgressBar(self) tempPB.setMinimumSize(50,21) tempPB.setMinimum(0) tempPB.setMaximum(100) tempPB.setTextVisible(True) tempPB.setFormat(str(arr[i])+" %p%") tempPB.setAlignment(Qt.AlignCenter) tempPB.setValue(0) if i==0: self.defaulStyle = tempPB.styleSheet() tempStatusLabel = QLabel(self) tempStatusLabel.setPixmap(self.okPix) tempStatusLabel.setMinimumSize(13,21) self.gridLayoutProgress.addWidget(tempCheckBox, pbCount+i, 0, 1, 1) self.gridLayoutProgress.addWidget(tempPB, pbCount+i, 1, 1, 1) self.gridLayoutProgress.addWidget(tempStatusLabel, pbCount+i, 2, 1, 1) self.gridLayoutProgress.addWidget(tempRemoveButton, pbCount+i, 3, 1, 1) self.removeGroupBox.addButton(tempRemoveButton, pbCount+i) self.pbList.append(tempPB) self.chList.append(tempCheckBox) self.lblList.append(tempStatusLabel) self.rmbList.append(tempRemoveButton) ''' Drag+Drop Functions ''' # The following three methods set up dragging and dropping for the app def dragEnterEvent(self, e): if e.mimeData().hasUrls: e.accept() else: e.ignore() def dragMoveEvent(self, e): if e.mimeData().hasUrls: e.accept() else: e.ignore() def dropEvent(self, e): """ Drop files directly onto the widget File locations are stored in fname :param e: :return: """ newFolders = [] if e.mimeData().hasUrls: e.setDropAction(Qt.CopyAction) e.accept() # Workaround for OSx dragging and dropping for url in e.mimeData().urls(): if op_sys == 'Darwin': #check for dir here as well fname = str(NSURL.URLWithString_(str(url.toString())).filePathURL().path()) else: fname = str(url.toLocalFile()) if os.path.isdir(fname) == True: newFolders.append(fname) #print(fname) #self.fname = fname #print(self.fname) #self.load_image() self.addNewFolders(newFolders) self.inList = self.inList + newFolders else: e.ignore() def addNewFolders(self, newFolders): self.addProgressBarUI(newFolders) self.setMinimumHeight(self.height()+len(newFolders)*32) #self.resize(self.width(),self.height()+200) self.update() self.adjustSize() self.setMinimumSize(self.size()) ''' Button Functions ''' def chooseAlpha(self, text): switcher={ "No Alpha":False, "with Alpha":True } self.alpha = switcher.get(text,"Invalid day of week") #print (self.alpha) def chooseCodec(self, text): switcher={ "UT Video":"utvideo" } self.codec = switcher.get(text,"Invalid day of week") #print (self.codec) def chooseFrameRate(self, text): self.frameRate = float(text) #print (self.frameRate) def currentData(self, widget): return widget.currentText() def radioBtnState(self, text): switcher={ 1:'Folder', 2:'File' } self.nameFrom = switcher.get(text,"Invalid day of week") #print(self.nameFrom) def removeButtonClicked(self, i): #print('remove trigger on id '+str(i)) #self.pbList.pop(i) ''' self.pbList[i].hide() self.chList[i].setChecked(False) self.chList[i].hide() self.lblList[i].hide() self.rmbList[i].hide() ''' print(self.gridLayoutProgress.rowCount()) self.pbList[i].setParent(None) self.chList[i].setChecked(False) self.chList[i].setParent(None) self.lblList[i].setParent(None) self.rmbList[i].setParent(None) self.removeGroupBox.removeButton(self.rmbList[i]) self.gridLayoutProgress.removeWidget(self.pbList[i]) self.gridLayoutProgress.removeWidget(self.chList[i]) self.gridLayoutProgress.removeWidget(self.lblList[i]) self.gridLayoutProgress.removeWidget(self.rmbList[i]) self.gridLayoutProgress.invalidate() self.gridLayoutProgress = QGridLayout() self.gridLayoutProgress.setVerticalSpacing(11) self.gridLayoutProgress.setHorizontalSpacing(6) self.gridLayoutProgress.setSizeConstraint(QLayout.SetDefaultConstraint) self.verticalLayout.insertLayout(1,self.gridLayoutProgress) print(self.gridLayoutProgress.rowCount()) ''' print(self.pbList) print(self.chList) print(self.lblList) print(self.rmbList) ''' self.pbList.pop(i) self.chList.pop(i) self.lblList.pop(i) self.rmbList.pop(i) self.inList.pop(i) #clear the gridLayout for j in reversed(range(len(self.pbList))): self.pbList[j].setParent(None) self.chList[j].setParent(None) self.lblList[j].setParent(None) self.rmbList[j].setParent(None) #reorder the gridLayout for j in range(len(self.pbList)): self.gridLayoutProgress.addWidget(self.chList[j], j, 0, 1, 1) self.gridLayoutProgress.addWidget(self.pbList[j], j, 1, 1, 1) self.gridLayoutProgress.addWidget(self.lblList[j], j, 2, 1, 1) self.gridLayoutProgress.addWidget(self.rmbList[j], j, 3, 1, 1) self.removeGroupBox.setId(self.rmbList[j],j) self.setMinimumHeight(self.height()-30) #self.setMinimumHeight(100) self.adjustSize() self.setMinimumSize(self.size()) print(self.gridLayoutProgress.rowCount()) #self.correctSize() ''' for j in range(len(self.removeGroupBox.buttons())): button = self.removeGroupBox.buttons()[j] #print(button) #print('original id '+str(self.removeGroupBox.id(button))) #print('new id '+str(j)) self.removeGroupBox.setId(button,j) ''' def correctSize(self): self.logText.show() self.gridLayoutDebug.removeItem(self.spacerItem) self.adjustSize() self.setMinimumSize(self.size()) self.repaint() self.gridLayoutDebug.addItem(self.spacerItem) self.logText.hide() self.setMinimumHeight(100) self.adjustSize() self.setMinimumSize(self.size()) def showDebugLog(self, bol): if bol: self.logText.show() self.hideShowLog.setText('Hide Log') self.gridLayoutDebug.removeItem(self.spacerItem) self.adjustSize() #self.resize(self.width(), self.height()+80) self.setMinimumSize(self.size()) else: self.gridLayoutDebug.addItem(self.spacerItem) self.logText.hide() self.hideShowLog.setText('Show Log') self.setMinimumHeight(100) self.adjustSize() self.setMinimumSize(self.size()) #self.resize(self.width(), 100) #self.setGeometry(0,0,self.width(),100) ''' Execution Functions ''' def execute_this_fn(self, path, codec, alpha, frameRate, nameFrom, i, progress_callback, errorFFMPEG_callback): #print(path) pyCompression = pyFFMEGCompress(path, codec, alpha, frameRate, nameFrom) ffProcess = pyCompression.ffmpegCompress() self.lblList[i].setPixmap(self.processingPix) #with kwargs kwargs = {'progress_callback':progress_callback, 'errorFFMPEG_callback':errorFFMPEG_callback} pyCompression.printProcess(ffProcess, **kwargs) return (pyCompression.debugString,pyCompression.error,i) def printOutput(self, s): print("Printing output "+ str(s)) def threadComplete(self, r): #print("THREAD COMPLETE! WITH ERROR " + str(r[2]) ) if r[1] == False: self.lblList[r[2]].setPixmap(self.goodPix) self.pbList[r[2]].setStyleSheet("QProgressBar::chunk {background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #44dd14,stop: 0.4999 #39c10f,stop: 0.5 #39c10f,stop: 1 #39c10f );border-radius: 3px; border: 1px solid #29880b;}QProgressBar{color:white}") self.pbList[r[2]].setValue(100) def errorPB(self, err): for i in range(len(self.pbList)): if self.pbList[i].format() == err: self.pbList[i].setValue(100) self.pbList[i].setStyleSheet("QProgressBar::chunk {background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #FF0350,stop: 0.4999 #FF0020,stop: 0.5 #FF0019,stop: 1 #FF0000 );border-radius: 3px; border: 1px solid #a60233;}QProgressBar{color:white}") self.pbList[i].setFormat(self.pbList[i].format()+" - Error") self.chList[i].setChecked(False) self.lblList[i].setPixmap(self.badPix) def resetProgressBar(self, pb, text, lbl): pb.setValue(0) pb.setFormat(text + ' %p%') pb.setStyleSheet(self.defaulStyle) lbl.setPixmap(self.okPix) def compressPress(self): for i in range(len(self.pbList)): if self.chList[i].isChecked(): self.resetProgressBar(self.pbList[i],self.inList[i],self.lblList[i]) worker = Worker(self.execute_this_fn, self.inList[i], self.codec, self.alpha, self.frameRate, self.nameFrom, i) # Any other args, kwargs are passed to the run function #worker.signals.result.connect(self.printOutput) worker.signals.result.connect(self.logText.appendPlainText) worker.signals.progress.connect(self.pbList[i].setValue) worker.signals.errorFFMPEG.connect(self.errorPB) worker.signals.error.connect(self.errorPB) worker.signals.finished.connect(self.threadComplete) #worker.signals.finished.connect(self.logText.appendPlainText) # Execute self.threadpool.start(worker) def exploreOutput(self): FILEBROWSER_PATH = os.path.join(os.getenv('WINDIR'), 'explorer.exe') explorePath = os.path.normpath('C:\\ExportedMOVs') subprocess.run([FILEBROWSER_PATH, explorePath])
def initUI(self): widget = QWidget() self.setCentralWidget(widget) hboxLayout = QHBoxLayout() widget.setLayout(hboxLayout) vboxWidget = QWidget() vboxLayout = QVBoxLayout() vboxWidget.setLayout(vboxLayout) hboxLayout.addWidget(vboxWidget) self.textField = QTextEdit() hboxLayout.addWidget(self.textField) fontSizeCb = QComboBox() for i in range(1, 42): fontSizeCb.addItem(str(i)) fontSizeCb.setCurrentText(str(12)) fontSizeCb.currentTextChanged.connect(self.changeFontSize) vboxLayout.addWidget(fontSizeCb) options = ['Times New Roman', 'Arial', 'Courier New'] rb = [QRadioButton(o) for o in options] cbg = QButtonGroup(self) cbg.setExclusive(True) for id, ch in enumerate(options): rb = QRadioButton(ch) if id == 1: rb.setChecked(True) cbg.addButton(rb) cbg.setId(rb, id) vboxLayout.addWidget(rb) cbg.buttonClicked.connect(self.changeFontType) self.textField.setFont(QFont('Arial', 12)) # colorGrid = QGridLayout() # colorPallete = QWidget() # colorPallete.setLayout(colorGrid) # vboxLayout.addWidget(colorPallete) # pb = [QPushButton(str(i)) for i in range(1, 20)] # for i in range(0, 3): # colorGrid.addWidget(pb[i * 5], i, 0) # colorGrid.addWidget(pb[i * 5 + 1], i, 1) # colorGrid.addWidget(pb[i * 5 + 2], i, 2) # colorGrid.addWidget(pb[i * 5 + 3], i, 3) # colorGrid.addWidget(pb[i * 5 + 4], i, 4) exitAction = QAction('Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.close) openAction = QAction('Open', self) openAction.setShortcut('Ctrl+O') openAction.setStatusTip('Open file') openAction.triggered.connect(self.openFile) newAction = QAction('New', self) newAction.setShortcut('Ctrl+N') newAction.setStatusTip('New') newAction.triggered.connect(self.newFile) saveAction = QAction('Save', self) saveAction.setShortcut('Ctrl+S') saveAction.setStatusTip('Save') saveAction.triggered.connect(self.saveFile) saveAsAction = QAction('Save As', self) saveAsAction.setStatusTip('Save As') saveAsAction.triggered.connect(self.saveFileDialog) menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(newAction) fileMenu.addAction(openAction) fileMenu.addAction(saveAction) fileMenu.addAction(saveAsAction) fileMenu.addAction(exitAction) cutAction = QAction('Cut', self) cutAction.setStatusTip('Cut') cutAction.setShortcut('Ctrl+X') cutAction.triggered.connect(self.cut) copyAction = QAction('Copy', self) cutAction.setStatusTip('Copy') cutAction.setShortcut('Ctrl+C') cutAction.triggered.connect(self.copy) editionMenu = menubar.addMenu('&Edition') editionMenu.addAction(cutAction) editionMenu.addAction(copyAction) toolbar = self.addToolBar('') toolbar.addAction(newAction) toolbar.addAction(openAction) toolbar.addAction(saveAction) toolbar.addAction(saveAsAction) toolbar.addAction(exitAction) self.setGeometry(500, 500, 500, 500) self.setWindowTitle('Notepad') self.show()
class MainWindow(QMainWindow, Ui_MainWindow): """ Class documentation goes here. """ def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget @type QWidget """ super(MainWindow, self).__init__(parent) self.setupUi(self) self.initialise() def initialise(self): self.side_view_init() self.combobox_init() self.current_window_init() self.connection = False def current_window_init(self): self.gv_setter.setStyleSheet( "border-image: url(:/side_btn/LightGCS_image/setter_pressed.png);") self.btns_flag = 1 self.stw_mainwindow.setCurrentIndex(0) self.stw_setter_sub.setCurrentIndex(0) def side_view_init(self): # flag for main window btns: # 0 for none # 1 for first # 2 for second # ... self.btns_flag = 0 # register event filter for all btns gv_btns = [ self.gv_setter, self.gv_monitor, self.gv_logger, self.gv_params, self.gv_exts ] gv_btns_images = [(1, "border-image: url(:/side_btn/LightGCS_image/setter.png);", \ "border-image: url(:/side_btn/LightGCS_image/setter_on.png);" , \ "border-image: url(:/side_btn/LightGCS_image/setter_pressed.png);"), \ (2, "border-image: url(:/side_btn/LightGCS_image/monitor.png);", \ "border-image: url(:/side_btn/LightGCS_image/monitor_on.png);" , \ "border-image: url(:/side_btn/LightGCS_image/monitor_pressed.png);"), \ (3, "border-image: url(:/side_btn/LightGCS_image/logger.png);", \ "border-image: url(:/side_btn/LightGCS_image/logger_on.png);", \ "border-image: url(:/side_btn/LightGCS_image/logger_pressed.png);"),\ (4, "border-image: url(:/side_btn/LightGCS_image/params.png);", \ "border-image: url(:/side_btn/LightGCS_image/params_on.png);" , \ "border-image: url(:/side_btn/LightGCS_image/params_pressed.png);"), \ (5, "border-image: url(:/side_btn/LightGCS_image/exts.png);", \ "border-image: url(:/side_btn/LightGCS_image/exts_on.png);" , \ "border-image: url(:/side_btn/LightGCS_image/exts_pressed.png);") ] self.gv_btns_res = dict(zip(gv_btns, gv_btns_images)) # register group view icon event filter for item in self.gv_btns_res.keys(): item.installEventFilter(self) # main window: setter view event self.gv_setter_init() self.gv_logger.mousePressEvent = self.on_logger_mouseClicked self.gv_monitor.mousePressEvent = self.on_monitor_mouseClicked self.gv_params.mousePressEvent = self.on_params_mouseClicked self.gv_exts.mousePressEvent = self.on_exts_mouseClicked def gv_setter_init(self): """ add push button here """ self.gv_setter.mousePressEvent = self.on_setter_mouseClicked self.setter_btns = [self.pb_firmware,\ self.pb_frame,\ self.pb_accel,\ self.pb_compass,\ self.pb_radio,\ self.pb_flt_mode,\ self.pb_pid,\ self.pb_peripheral] self.setter_btn_clicked(self.pb_firmware) def setter_btn_clicked(self, obj): self.setter_btn_reset() obj.setStyleSheet("background-color: rgb(0,170,0)") idx = self.setter_btns.index(obj) self.stw_setter_sub.setCurrentIndex(idx) def setter_btn_reset(self): for item in self.setter_btns: item.setStyleSheet( "background-color: rgb(225, 225, 225);\ncolor: rgb(0, 0, 0);") def combobox_init(self): self.combobox_port_init() self.combobox_baudrate_init() self.motor_db_combobox_init() def find_ports(self): self.preferred_list = [ '*FTDI*', "*Arduino_Mega_2560*", "*3D_Robotics*", "*USB to UART*", '*PX4*', '*FMU*' ] self.serial_list = mavutil.auto_detect_serial(self.preferred_list) if self.serial_list: pass else: self.serial_list = mavutil.auto_detect_serial() for port in self.serial_list: # print port.__dict__ if 'Virtual' in port.description: self.serial_list.remove(port) try: self.serial_list_device = [] for item in self.serial_list: self.serial_list_device.append(item.device) except Exception as e: pass def combobox_port_update(self): self.cb_comm_name.clear() self.find_ports() if self.serial_list_device: self.cb_comm_name.addItems(self.serial_list_device) if len(self.serial_list_device) == 1: self.cb_comm_name.setCurrentText(self.serial_list_device[0]) else: self.cb_comm_name.addItem("No FMU PORT") self.cb_comm_name.setCurrentText("No FMU PORT") def combobox_port_init(self): # register com port event filter self.cb_comm_name.installEventFilter(self) self.combobox_port_update() def combobox_baudrate_init(self): self.serial_baud = [ "1200", "2400", "4800", "9600", "38400", "57600", "111100", "115200", "500000", "921600", "1500000" ] self.cb_comm_rate.addItems(self.serial_baud) self.cb_comm_rate.setCurrentIndex(7) def eventFilter(self, obj, e): if obj in self.gv_btns_res.keys(): values = self.gv_btns_res.get(obj) if not self.btns_flag == values[0]: if e.type() == QEvent.Enter: obj.setStyleSheet(values[2]) # e.g. setter_on.png return True elif e.type() == QEvent.Leave: obj.setStyleSheet(values[1]) # e.g. setter.png return True if obj == self.cb_comm_name: if e.type() == QEvent.MouseButtonPress: self.combobox_port_update() return False if obj in self.motorCbs: if e.type() == QEvent.MouseButtonPress: self.motor_data_combobox_update(obj) return False return False def reset_gv_btns_icon(self): for item, values in self.gv_btns_res.items(): item.setStyleSheet(values[1]) def on_mouse_pressed_gv_btns(self, obj, e): if Qt.LeftButton == e.button(): self.reset_gv_btns_icon() values = self.gv_btns_res.get(obj) self.btns_flag = values[0] obj.setStyleSheet(values[3]) self.stw_mainwindow.setCurrentIndex(self.btns_flag - 1) def on_setter_mouseClicked(self, e): self.on_mouse_pressed_gv_btns(self.gv_setter, e) def on_logger_mouseClicked(self, e): self.on_mouse_pressed_gv_btns(self.gv_logger, e) # self.stw_mainwindow.setCurrentIndex(1) @pyqtSlot() def on_pb_read_log_clicked(self): self.read_data_flash_file() def on_monitor_mouseClicked(self, e): self.on_mouse_pressed_gv_btns(self.gv_monitor, e) def on_params_mouseClicked(self, e): self.on_mouse_pressed_gv_btns(self.gv_params, e) def on_exts_mouseClicked(self, e): self.on_mouse_pressed_gv_btns(self.gv_exts, e) self.exts_window_init() @pyqtSlot() def on_pb_params_table_clicked(self): self.stw_params_sub.setCurrentIndex(0) if not self.connection: return self.table_view_init() @pyqtSlot(QString) def on_cb_comm_name_currentIndexChanged(self, p0): self.current_port = p0 @pyqtSlot(QString) def on_cb_comm_rate_currentIndexChanged(self, p0): self.current_baud = int(p0) def pb_connection_reset(self): self.pb_connection.setText("未连接") self.pb_connection.setStyleSheet( "background-color: rgb(204, 204, 102);\ncolor: rgb(0,0,0)") @pyqtSlot() def on_pb_connection_clicked(self): if not self.serial_list: self.tb_console.append(self.cb_comm_name.currentText() + " No Valid FMU!") # print self.cb_comm_name.currentText() return False port = self.cb_comm_name.currentText() if not port in self.serial_list_device: return False if not self.connection: try: self.vehicle = connect(port, wait_ready=True, status_printer=self.tb_console.append, baud=int( self.cb_comm_rate.currentText())) except Exception as e: self.vehicle = None # print str(e) if self.vehicle: self.connection = True self.pb_connection.setText("已连接") self.pb_connection.setStyleSheet( "background-color: rgb(51, 153, 51);") else: self.pb_connection_reset() else: self.pb_connection_reset() self.connection = False self.vehicle.close() @pyqtSlot() def on_pb_firmware_clicked(self): """ Upload mav firmware to flight board """ self.setter_btn_clicked(self.pb_firmware) @pyqtSlot() def on_pb_frame_clicked(self): """ Set mav frame class or type """ self.setter_btn_clicked(self.pb_frame) @pyqtSlot() def on_pb_accel_clicked(self): """ enter accelerator calibrating window """ self.setter_btn_clicked(self.pb_accel) @pyqtSlot() def on_pb_compass_clicked(self): """ enter compass calibrating window """ self.setter_btn_clicked(self.pb_compass) @pyqtSlot() def on_pb_radio_clicked(self): """ enter rc calibrating window """ self.setter_btn_clicked(self.pb_radio) @pyqtSlot() def on_pb_flt_mode_clicked(self): """ enter flight mode setting window """ self.setter_btn_clicked(self.pb_flt_mode) @pyqtSlot() def on_pb_pid_clicked(self): """ enter pid params window """ self.setter_btn_clicked(self.pb_pid) @pyqtSlot() def on_pb_copter_pid_screen_clicked(self): """ read fixedwing pid params """ pass # import setting.pid_params @pyqtSlot() def on_pb_fixedwing_pid_screen_clicked(self): """ read fixedwing pid params """ if not self.connection: return from setting import pid_params pid_params.fwPID(self.vehicle.parameters, self.f_pid) @pyqtSlot() def on_pb_peripheral_clicked(self): """ Slot documentation goes here. """ self.setter_btn_clicked(self.pb_peripheral) @pyqtSlot() def on_pb_custom_fw_clicked(self): self.custom_fw_select_event() def exts_window_init(self): self.ext_btns_init() def ext_btns_init(self): self.ext_btns = QButtonGroup(self) self.ext_btns.setExclusive(True) # 附加功能选项按顺序添加到此列表 ext_btns_list = [ self.rb_xrotor_calc, self.rb_fixedwing_calc, self.rb_tiltrotor_calc, self.rb_rotor_database, self.rb_foc_esc ] for i in range(len(ext_btns_list)): self.ext_btns.addButton(ext_btns_list[i]) self.ext_btns.setId(ext_btns_list[i], i) self.ext_btns.buttonClicked.connect(self.ext_btns_update) self.rb_xrotor_calc.setChecked(True) self.stw_exts_sub.setCurrentIndex(0) self.xrotor_params_init() def ext_btns_update(self, button): id = self.ext_btns.checkedId() self.stw_exts_sub.setCurrentIndex(id) if id == 0 and not "xrotor_initialised" in self.__dict__: self.xrotor_params_init() elif id == 1 and not "fixed_wing_initialised" in self.__dict__: self.fixed_wing_params_init() elif id == 2 and not "tilt_rotor_initialised" in self.__dict__: self.tilt_rotor_params_init() elif id == 3 and not "motor_db_initialised" in self.__dict__: self.motor_db_init() elif id == 4 and not "foc_esc_initialised" in self.__dict__: pass else: pass @pyqtSlot() def on_pb_xrotor_calc_clicked(self): self.copter_estimator() @pyqtSlot() def on_pb_xrotor_reset_clicked(self): """ Slot documentation goes here. """ for i in range(len(self.xrotor_params)): if isinstance(self.xrotor_params[i], QComboBox): self.xrotor_params[i].setCurrentText("") else: self.xrotor_params[i].setText("") def fixed_wing_params_init(self): """ 固定翼机评估部分 """ self.fixed_wing_initialised = True def tilt_rotor_params_init(self): """ 倾旋翼机评估部分 """ self.tilt_rotor_initialised = True @pyqtSlot() def on_pb_motor_db_doc_select_clicked(self): """ Slot documentation goes here. """ self.motor_dir = QFileDialog.getExistingDirectory(self, "选择电机测试数据目录", \ "",\ QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks) self.label_motor_db_path.setText(self.motor_dir) @pyqtSlot() def on_pb_motor_db_file_read_clicked(self): self.motor_db_file_read_event() @pyqtSlot() def on_pb_motor_db_file_insert_clicked(self): self.motor_db_file_insert_event() @pyqtSlot() def on_pb_motor_db_file_remove_clicked(self): self.motor_db_file_remove_event() @pyqtSlot() def on_pb_csv_template_clicked(self): self.csv_template_event() @pyqtSlot() def on_pb_motor_db_insert_confirm_clicked(self): self.motor_db_insert_confirm_event() @pyqtSlot(QString) def on_cb_motor_db_productor_currentTextChanged(self, p0): self.motorCbValues[0] = p0 @pyqtSlot(QString) def on_cb_motor_db_type_currentTextChanged(self, p0): self.motorCbValues[1] = p0 @pyqtSlot(QString) def on_cb_motor_db_kv_currentTextChanged(self, p0): self.motorCbValues[2] = p0 @pyqtSlot(QString) def on_cb_motor_db_propeller_currentTextChanged(self, p0): self.motorCbValues[3] = p0 @pyqtSlot(QString) def on_cb_motor_db_volt_currentTextChanged(self, p0): self.motorCbValues[4] = p0 @pyqtSlot() def on_pb_motor_data_sql_clicked(self): self.motor_data_sql_event() @pyqtSlot() def on_pb_motor_table_show_clicked(self): self.motor_table_show_event() @pyqtSlot() def on_pb_motor_db_update_clicked(self): self.motor_table_view_model.database().transaction() #开始事务操作 if self.motor_table_view_model.submitAll(): self.motor_table_view_model.database().commit() #提交 else: self.motor_table_view_model.database().rollback() #回滚 QMessageBox.warning(self, "tableModel",\ "数据库错误: {}".format(self.motor_table_view_model.lastError().text())) @pyqtSlot() def on_pb_motor_db_insert_row_clicked(self): pass @pyqtSlot() def on_pb_motor_db_delete_row_clicked(self): pass
def request_trezor_init_settings(self, wizard, method, device_id): vbox = QVBoxLayout() next_enabled = True devmgr = self.device_manager() client = devmgr.client_by_id(device_id) if not client: raise Exception(_("The device was disconnected.")) model = client.get_trezor_model() fw_version = client.client.version # label label = QLabel(_("Enter a label to name your device:")) name = QLineEdit() hl = QHBoxLayout() hl.addWidget(label) hl.addWidget(name) hl.addStretch(1) vbox.addLayout(hl) # word count gb = QGroupBox() hbox1 = QHBoxLayout() gb.setLayout(hbox1) vbox.addWidget(gb) gb.setTitle(_("Select your seed length:")) bg_numwords = QButtonGroup() word_counts = (12, 18, 24) for i, count in enumerate(word_counts): rb = QRadioButton(gb) rb.setText(_("{:d} words").format(count)) bg_numwords.addButton(rb) bg_numwords.setId(rb, i) hbox1.addWidget(rb) rb.setChecked(True) # PIN cb_pin = QCheckBox(_('Enable PIN protection')) cb_pin.setChecked(True) vbox.addWidget(WWLabel(RECOMMEND_PIN)) vbox.addWidget(cb_pin) # "expert settings" button expert_vbox = QVBoxLayout() expert_widget = QWidget() expert_widget.setLayout(expert_vbox) expert_widget.setVisible(False) expert_button = QPushButton(_("Show expert settings")) def show_expert_settings(): expert_button.setVisible(False) expert_widget.setVisible(True) expert_button.clicked.connect(show_expert_settings) vbox.addWidget(expert_button) # passphrase passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT) passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN) passphrase_warning.setStyleSheet("color: red") cb_phrase = QCheckBox(_('Enable passphrases')) cb_phrase.setChecked(False) expert_vbox.addWidget(passphrase_msg) expert_vbox.addWidget(passphrase_warning) expert_vbox.addWidget(cb_phrase) # ask for recovery type (random word order OR matrix) bg_rectype = None if method == TIM_RECOVER and not model == 'T': gb_rectype = QGroupBox() hbox_rectype = QHBoxLayout() gb_rectype.setLayout(hbox_rectype) expert_vbox.addWidget(gb_rectype) gb_rectype.setTitle(_("Select recovery type:")) bg_rectype = QButtonGroup() rb1 = QRadioButton(gb_rectype) rb1.setText(_('Scrambled words')) bg_rectype.addButton(rb1) bg_rectype.setId(rb1, RECOVERY_TYPE_SCRAMBLED_WORDS) hbox_rectype.addWidget(rb1) rb1.setChecked(True) rb2 = QRadioButton(gb_rectype) rb2.setText(_('Matrix')) bg_rectype.addButton(rb2) bg_rectype.setId(rb2, RECOVERY_TYPE_MATRIX) hbox_rectype.addWidget(rb2) # no backup cb_no_backup = None if method == TIM_NEW: cb_no_backup = QCheckBox(f'''{_('Enable seedless mode')}''') cb_no_backup.setChecked(False) if (model == '1' and fw_version >= (1, 7, 1) or model == 'T' and fw_version >= (2, 0, 9)): cb_no_backup.setToolTip(SEEDLESS_MODE_WARNING) else: cb_no_backup.setEnabled(False) cb_no_backup.setToolTip(_('Firmware version too old.')) expert_vbox.addWidget(cb_no_backup) vbox.addWidget(expert_widget) wizard.exec_layout(vbox, next_enabled=next_enabled) return TrezorInitSettings( word_count=word_counts[bg_numwords.checkedId()], label=name.text(), pin_enabled=cb_pin.isChecked(), passphrase_enabled=cb_phrase.isChecked(), recovery_type=bg_rectype.checkedId() if bg_rectype else None, no_backup=cb_no_backup.isChecked() if cb_no_backup else False, )
def request_trezor_init_settings(self, wizard, method, model): vbox = QVBoxLayout() next_enabled = True label = QLabel(_("Enter a label to name your device:")) name = QLineEdit() hl = QHBoxLayout() hl.addWidget(label) hl.addWidget(name) hl.addStretch(1) vbox.addLayout(hl) def clean_text(widget): text = widget.toPlainText().strip() return ' '.join(text.split()) gb = QGroupBox() hbox1 = QHBoxLayout() gb.setLayout(hbox1) vbox.addWidget(gb) gb.setTitle(_("Select your seed length:")) bg_numwords = QButtonGroup() for i, count in enumerate([12, 18, 24]): rb = QRadioButton(gb) rb.setText(_("%d words") % count) bg_numwords.addButton(rb) bg_numwords.setId(rb, i) hbox1.addWidget(rb) rb.setChecked(True) cb_pin = QCheckBox(_('Enable PIN protection')) cb_pin.setChecked(True) vbox.addWidget(WWLabel(RECOMMEND_PIN)) vbox.addWidget(cb_pin) passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT) passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN) passphrase_warning.setStyleSheet("color: red") cb_phrase = QCheckBox(_('Enable passphrases')) cb_phrase.setChecked(False) vbox.addWidget(passphrase_msg) vbox.addWidget(passphrase_warning) vbox.addWidget(cb_phrase) # ask for recovery type (random word order OR matrix) if method == TIM_RECOVER and not model == 'T': gb_rectype = QGroupBox() hbox_rectype = QHBoxLayout() gb_rectype.setLayout(hbox_rectype) vbox.addWidget(gb_rectype) gb_rectype.setTitle(_("Select recovery type:")) bg_rectype = QButtonGroup() rb1 = QRadioButton(gb_rectype) rb1.setText(_('Scrambled words')) bg_rectype.addButton(rb1) bg_rectype.setId(rb1, RECOVERY_TYPE_SCRAMBLED_WORDS) hbox_rectype.addWidget(rb1) rb1.setChecked(True) rb2 = QRadioButton(gb_rectype) rb2.setText(_('Matrix')) bg_rectype.addButton(rb2) bg_rectype.setId(rb2, RECOVERY_TYPE_MATRIX) hbox_rectype.addWidget(rb2) else: bg_rectype = None wizard.exec_layout(vbox, next_enabled=next_enabled) item = bg_numwords.checkedId() pin = cb_pin.isChecked() recovery_type = bg_rectype.checkedId() if bg_rectype else None return (item, name.text(), pin, cb_phrase.isChecked(), recovery_type)
class DataCheck(Content): def __init__(self, parent=None, button_func=None, params=None): super().__init__(parent, 'Data check', params) self.button_func = button_func path = os.path.abspath(os.path.dirname(__file__)) + '/static/' # nr = min(5, data.shape[0]) nr = len(self.params.data5) if params.lang == 'jp': text = ('データの読み込み結果(先頭{n}行)を以下に示します.\n' 'データを正しく読み込めていることを確認してください.'.format(n=nr)) self.set_paragraph( 'データ読み込み結果の確認', text=text) else: text = ('First {n} rows of your data are shown below.\n' 'Confirm that the data was read correctly.'.format(n=nr)) self.set_paragraph( 'Check data', text=text) table = NonScrollTable(self.inner) table.setRowCount(nr) table.setColumnCount(len(self.params.columns)) table.setHorizontalHeaderLabels(self.params.columns) for r in range(nr): for c in range(len(self.params.columns)): item = QTableWidgetItem(str(self.params.data5.iat[r, c])) item.setFlags(Qt.ItemIsEnabled) table.setItem(r, c, item) table.setNonScroll() self.vbox.addWidget(table) # Text for type checking and objective variable setting path1 = path + 'categorical' text = self.get_text(path1) if self.params.lang == 'en': self.set_paragraph( 'Check type of variables and set objective variable', text=text) else: self.set_paragraph('変数タイプの確認と目的変数の設定', text=text) # htable = QTableWidget(self.inner) htable = NonScrollTable(self.inner) htable.setRowCount(len(self.params.columns)) htable.setColumnCount(4) htable.setHorizontalHeaderLabels( ['columns', 'categorical', 'numerical', 'target']) self.lst_cat = [] self.lst_num = [] self.lst_obj = [] self.obj_group = QButtonGroup(self.inner) for c in range(len(self.params.columns)): # col 1 item = QTableWidgetItem(self.params.columns[c]) item.setFlags(Qt.ItemIsEnabled) htable.setItem(c, 0, item) group = QButtonGroup(self.inner) # col 2 htable.setCellWidget( c, 1, self.__make_cell(c, 'cat', self.params.col_types[c], self.params.col_types_def[c])) group.addButton(self.lst_cat[-1]) # col 3 htable.setCellWidget( c, 2, self.__make_cell(c, 'num', self.params.col_types[c], self.params.col_types_def[c])) group.addButton(self.lst_num[-1]) # col 4 htable.setCellWidget( c, 3, self.__make_cell(c, 'obj', self.params.col_types[c], self.params.col_types_def[c])) self.obj_group.addButton(self.lst_obj[-1]) self.obj_group.setId(self.lst_obj[-1], c) htable.setNonScroll() self.vbox.addWidget(htable) if self.params.lang == 'jp': self.txt_cnf = ('<font color="red">目的変数を1つ選択し,' 'targetの列にチェックをいれてください。') if self.params.task.lower() == 'classification': self.txt_cnf += '<br>目的変数はカテゴリ変数である必要があります。</font>' else: self.txt_cnf += '<br>目的変数は量的変数である必要があります。</font>' else: self.txt_cnf = ('<font color="red">Select one variable as target variable,' 'then set the column of "target" of the variable checked.') if self.params.task.lower() == 'classification': self.txt_cnf += '<br>Target variable must be a categorical variable.</font>' else: self.txt_cnf += '<br>Target variable must be a numerical variable.</font>' self.lbl_cnf = QLabel(self.txt_cnf, self.inner) self.vbox.addWidget(self.lbl_cnf) self.vbox.addStretch(1) self.btn = QPushButton('Next', self.inner) self.btn.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};') if self.params.lang == 'en': self.btn.clicked.connect(lambda: self.button_func('Overfitting')) else: self.btn.clicked.connect(lambda: self.button_func('過学習')) if self.obj_group.checkedButton() is None: self.btn.setEnabled(False) else: self.lbl_cnf.setText('<br>') self.btn.setEnabled(True) self.vbox.addWidget(self.btn) def __make_cell(self, c, name, col_type, col_type_def): cell = QWidget(self.inner) rbtn = QRadioButton('', cell) rbtn.toggled.connect(lambda: self.rbtn_clicked(name + '_' + str(c))) hbl = QHBoxLayout(cell) hbl.addWidget(rbtn) hbl.setContentsMargins(0, 0, 0, 0) hbl.setAlignment(Qt.AlignCenter) cell.setLayout(hbl) if name == 'cat': if col_type == 'object': rbtn.setChecked(True) self.lst_cat.append(rbtn) elif name == 'num': if col_type != 'object': rbtn.setChecked(True) if col_type_def == 'object': rbtn.setEnabled(False) self.lst_num.append(rbtn) elif name == 'obj': if col_type == 'object' and self.params.task == 'Regression': rbtn.setEnabled(False) elif col_type != 'object' and self.params.task == 'Classification': rbtn.setEnabled(False) if self.params.columns[c] == self.params.objective: rbtn.setChecked(True) self.lst_obj.append(rbtn) return cell def rbtn_clicked(self, text): name, idx = text.split('_') idx = int(idx) if len(self.lst_obj) <= idx: return if self.lst_num[idx].isChecked(): if self.params.task == 'Classification': self.obj_group.setExclusive(False) self.lst_obj[idx].setChecked(False) self.obj_group.setExclusive(True) self.lst_obj[idx].setEnabled(False) elif self.params.task == 'Regression': self.lst_obj[idx].setEnabled(True) self.params.col_types[idx] = self.params.col_types_def[idx] elif self.lst_cat[idx].isChecked(): if self.params.task == 'Classification': self.lst_obj[idx].setEnabled(True) elif self.params.task == 'Regression': self.obj_group.setExclusive(False) self.lst_obj[idx].setChecked(False) self.obj_group.setExclusive(True) self.lst_obj[idx].setEnabled(False) self.params.col_types[idx] = 'object' if self.obj_group.checkedButton() is None: self.params.objective = None self.lbl_cnf.setText(self.txt_cnf) self.btn.setEnabled(False) else: self.params.objective =\ self.params.columns[self.obj_group.checkedId()] self.lbl_cnf.setText('<br>') self.btn.setEnabled(True) self.params.col_types_changed = True
class SetSaveFormatDialog(QDialog): def __init__(self, initSaveFormat, initSaveTemperature, initSaveTtlOut, initNewSaveFilePeriodMinutes, parent): super().__init__(parent) self.setWindowTitle("Select Saved Data File Format") saveFormatIntanButton = QRadioButton("Traditional Intan File Format") saveFormatNeuroScopeButton = QRadioButton( "\"One File Per Signal Type\" Format") saveFormatOpenEphysButton = QRadioButton( "\"One File Per Channel\" Format") self.buttonGroup = QButtonGroup() self.buttonGroup.addButton(saveFormatIntanButton) self.buttonGroup.addButton(saveFormatNeuroScopeButton) self.buttonGroup.addButton(saveFormatOpenEphysButton) self.buttonGroup.setId(saveFormatIntanButton, constants.SaveFormatIntan) self.buttonGroup.setId(saveFormatNeuroScopeButton, constants.SaveFormatFilePerSignalType) self.buttonGroup.setId(saveFormatOpenEphysButton, constants.SaveFormatFilePerChannel) if initSaveFormat == constants.SaveFormatIntan: saveFormatIntanButton.setChecked(True) elif initSaveFormat == constants.SaveFormatFilePerSignalType: saveFormatNeuroScopeButton.setChecked(True) elif initSaveFormat == constants.SaveFormatFilePerChannel: saveFormatOpenEphysButton.setChecked(True) self.recordTimeSpinBox = QSpinBox() self.recordTimeSpinBox.setRange(1, 999) self.recordTimeSpinBox.setValue(initNewSaveFilePeriodMinutes) self.saveTemperatureCheckBox = QCheckBox( "Save On-Chip Temperature Sensor Readings") self.saveTemperatureCheckBox.setChecked(initSaveTemperature) self.saveTtlOutCheckBox = QCheckBox("Save Digital Outputs") self.saveTtlOutCheckBox.setChecked(initSaveTtlOut) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) newFileTimeLayout = QHBoxLayout() newFileTimeLayout.addWidget(QLabel("Start file every")) newFileTimeLayout.addWidget(self.recordTimeSpinBox) newFileTimeLayout.addWidget(QLabel("minutes")) newFileTimeLayout.addStretch(1) label1 = QLabel( "This option saves all waveforms in one file, along with records " "of sampling rate, amplifier bandwidth, channel names, etc. To keep " "individual file size reasonable, a file is created every N minutes. " "These *.rhd data files may be read into MATLAB using " "read_Intan_RHD2000_file.m, provided on the Intan web site.") label1.setWordWrap(True) label2 = QLabel( "This option creates a subdirectory and saves raw data files for each " "signal type: amplifiers, auxiliary inputs, supply voltages, board " "ADC inputs, and board digital inputs. For example, the amplifier.dat " "file contains waveform data from all enabled amplifier channels. The " "time.dat file contains the timestamp vector, and an info.rhd file contains " "records of sampling rate, amplifier bandwidth, channel names, etc." ) label2.setWordWrap(True) label2b = QLabel( "These raw data files are compatible with the NeuroScope software package." ) label2b.setWordWrap(True) label3 = QLabel( "This option creates a subdirectory and saves each enabled waveform " "in its own *.dat raw data file. The subdirectory also contains a time.dat " "file containing a timestamp vector, and an info.rhd file containing " "records of sampling rate, amplifier bandwidth, channel names, etc." ) label3.setWordWrap(True) boxLayout1 = QVBoxLayout() boxLayout1.addWidget(saveFormatIntanButton) boxLayout1.addWidget(label1) boxLayout1.addLayout(newFileTimeLayout) boxLayout1.addWidget(self.saveTemperatureCheckBox) boxLayout2 = QVBoxLayout() boxLayout2.addWidget(saveFormatNeuroScopeButton) boxLayout2.addWidget(label2) boxLayout2.addWidget(label2b) boxLayout3 = QVBoxLayout() boxLayout3.addWidget(saveFormatOpenEphysButton) boxLayout3.addWidget(label3) mainGroupBox1 = QGroupBox() mainGroupBox1.setLayout(boxLayout1) mainGroupBox2 = QGroupBox() mainGroupBox2.setLayout(boxLayout2) mainGroupBox3 = QGroupBox() mainGroupBox3.setLayout(boxLayout3) label4 = QLabel( "To minimize the disk space required for data files, remember to " "disable all unused channels, including auxiliary input and supply " "voltage channels, which may be found by scrolling down below " "amplifier channels in the multi-waveform display.") label4.setWordWrap(True) label5 = QLabel( "For detailed information on file formats, see the " "<b>RHD2000 Application note: Data file formats</b>, " "available at <i>http://www.intantech.com/downloads.html</i>") label5.setWordWrap(True) mainLayout = QVBoxLayout() mainLayout.addWidget(mainGroupBox1) mainLayout.addWidget(mainGroupBox2) mainLayout.addWidget(mainGroupBox3) mainLayout.addWidget(self.saveTtlOutCheckBox) mainLayout.addWidget(label4) mainLayout.addWidget(label5) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout)
class PstnSettingsWidget(QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.layout = QVBoxLayout() self.form_layout = QFormLayout() self.setup_heading() self.button_group = QGroupBox("Mandatory Fields are Marked with *") self.layout.addWidget(self.button_group) self.v_box = QVBoxLayout() self.button_group.setLayout(self.v_box) self.setup_pstn_settings_form() self.v_box.addLayout(self.form_layout) self.setup_ip_form() self.v_box.addLayout(self.ip_form_layout) self.init_settings() self.setup_buttons() self.v_box.addWidget(QLabel()) self.v_box.addLayout(self.button_layout) self.setLayout(self.layout) def setup_buttons(self): self.button_layout = QHBoxLayout() back_button_creator = BackButton() self.back_button = back_button_creator.create_back_button() self.button_layout.addWidget(self.back_button) self.add_ip_address_button = QPushButton("Add IP Address", self) self.add_ip_address_button.setToolTip("Add another contact IP address") self.button_layout.addWidget(self.add_ip_address_button) self.apply_settings_button = QPushButton("Apply") self.apply_settings_button.setToolTip( "Update Sip Trunk settings for contact between your IVR and telephone provider") self.button_layout.addWidget(self.apply_settings_button) def setup_ip_form(self): self.ip_form_layout = QFormLayout() self.ip_addresses = [] self.delete_button_group = QButtonGroup(self) self.delete_layouts = [] self.settings = QSettings("gp_ivr_settings", "GP_IVR_Settings") def setup_pstn_settings_form(self): self.form_layout.addRow("", QLabel()) self.pjsip_port = QLineEdit() self.pjsip_port.setToolTip("The port that your telephone provider will connect to the IVR with") self.provider_address = QLineEdit() self.provider_address.setToolTip("The SIP address that the IVR can contact the telephone provider through") self.provider_port = QLineEdit() self.provider_port.setToolTip("The port through which the telephone provider uses in communications") self.form_layout.addRow("Asterisk PJSIP Port (default is 5160):", self.pjsip_port) self.form_layout.addRow("*Provider Contact Address:", self.provider_address) self.form_layout.addRow("Provider Contact Port:", self.provider_port) grow_label = QLabel() self.form_layout.addRow("Provider Contact IP Addresses:", grow_label) grow_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) def setup_heading(self): heading_font = QFont('Arial', 12) heading_font.setBold(True) heading = QLabel("SIP Trunk Settings:") heading.setFont(heading_font) self.layout.addWidget(QLabel()) self.layout.addWidget(heading) page_info = QLabel( "You can change your telephone service provider SIP trunk settings here.\nThese settings must be updated from the default before running an IVR.\nMake sure that you have created a SIP trunk with your telephone provider.") self.layout.addWidget(page_info) self.layout.addWidget(QLabel()) def init_settings(self): self.pjsip_port.setText(self.settings.value("pjsip port")) self.provider_address.setText(self.settings.value("provider contact address")) self.provider_port.setText(self.settings.value("provider contact port")) saved_ip_addresses = self.settings.value("provider ip addresses") if saved_ip_addresses is not None: new_ip_addresses = list(saved_ip_addresses.split(",")) del new_ip_addresses[-1] for ip_address in new_ip_addresses: self.add_ip_address(value=ip_address) def add_ip_address(self, value=None): layout = QHBoxLayout() delete_ip_address_button = QPushButton("Delete", self) delete_ip_address_button.setToolTip("Remove this contact IP address") new_ip_address = QLineEdit() new_ip_address.setToolTip("IP address that the telephone provider will contact the IVR with") layout.addWidget(new_ip_address) layout.addWidget(delete_ip_address_button) if value is not None: new_ip_address.setText(value) self.ip_form_layout.addRow("IP Address " + str(len(self.ip_addresses)), layout) self.ip_addresses.append(new_ip_address) self.delete_button_group.addButton(delete_ip_address_button) def apply_settings(self): self.save_settings() ip_addresses = [] if not self.pjsip_port.text(): pjsip_port_text = "5160" else: pjsip_port_text = self.pjsip_port.text() if not self.provider_port.text(): provider_port_text = "5060" else: provider_port_text = self.provider_port.text() for ip_address in self.ip_addresses: ip_addresses.append(ip_address.text()) create_pjsip = SettingsToPjsip(asterisk_constants.PJSIP_CONF_PATH, pjsip_port_text, self.provider_address.text(), provider_port_text, ip_addresses) create_pjsip.create_config() def save_settings(self): self.settings.setValue("pjsip port", self.pjsip_port.text()) self.settings.setValue("provider contact address", self.provider_address.text()) self.settings.setValue("provider contact port", self.provider_port.text()) ip_address_list = "" for ip_address in self.ip_addresses: ip_address_list += ip_address.text() + "," if ip_address_list is not None: self.settings.setValue("provider ip addresses", ip_address_list) def delete_ip_address(self, button): ip_index = - 2 - self.delete_button_group.id(button) self.ip_form_layout.removeRow(ip_index) del self.ip_addresses[ip_index] for button in self.delete_button_group.buttons(): button_id = self.delete_button_group.id(button) if(button_id < - 2 - ip_index): self.delete_button_group.setId(button, button_id + 1)
class sequence_class(QWidget): send_sequence = QtCore.pyqtSignal(list) def __init__(self, parent): super(QWidget, self).__init__(parent) parent.send_sequenceActual.connect(self.addSequence) parent.send_sequenceSim.connect(self.simulation) parent.send_sequenceSetAct.connect(self.setAct) self.n = 0 self.buttGo = [] self.buttGoGroup = QButtonGroup() self.buttGoGroup.buttonClicked[int].connect(self.buttGoDef) self.buttClear = [] self.buttClearGroup = QButtonGroup() self.buttClearGroup.buttonClicked[int].connect(self.buttClearDef) self.sequence_layout = QVBoxLayout(self) self.createTable() self.sequence_layout.addWidget(self.tableWidget) self.setLayout(self.sequence_layout) def buttGoDef(self, i): self.send_sequence.emit(dataSequence[i]) self.tableWidget.selectRow(i) def buttClearDef(self, i): try: for j in range(i, len(dataSequence) - 1): self.buttClear[j] = self.buttClear[j + 1] self.buttClearGroup.setId(self.buttClear[j + 1], (j)) self.buttGo[j] = self.buttGo[j + 1] self.buttGoGroup.setId(self.buttGo[j + 1], (j)) dataSequence.pop(i) self.tableWidget.removeRow(i) self.n -= 1 except: print("error") def setAct(self, act): self.tableWidget.selectRow(act) def simulation(self, sim): if sim == 0: for i in range(7): self.tableWidget.setColumnWidth(i, 59) if sim == 1: for i in range(7): self.tableWidget.setColumnWidth(i, 104) def addSequence(self, dataRet): data = [] data.extend(dataRet) dataSequence.append(data) self.buttGo.append(self.n) self.buttGo[self.n] = QPushButton("Go") self.buttClear.append(self.n) self.buttClear[self.n] = QPushButton("Remove") self.n += 1 self.tableWidget.setRowCount(self.n) for i in range(len(dataRet)): self.tableWidget.setItem(self.n - 1, i, QTableWidgetItem(str(dataRet[i]))) self.tableWidget.setCellWidget(self.n - 1, i + 1, self.buttGo[self.n - 1]) self.tableWidget.setCellWidget(self.n - 1, i + 2, self.buttClear[self.n - 1]) self.tableWidget.setRowHeight(self.n - 1, 20) self.tableWidget.selectRow(self.n - 1) self.buttGoGroup.addButton(self.buttGo[self.n - 1], self.n - 1) self.buttClearGroup.addButton(self.buttClear[self.n - 1], self.n - 1) def createTable(self): self.tableWidget = QTableWidget() self.tableWidget.setRowCount(0) self.tableWidget.setColumnCount(7) label = ['x [mm]', 'y [mm]', 'z [mm]', 'α [°]', 'stop [s]', ' ', ' '] self.tableWidget.setHorizontalHeaderLabels(label) self.tableWidget.itemChanged.connect(self.on_click) def on_click(self): for currentQTableWidgetItem in self.tableWidget.selectedItems(): dataSequence[currentQTableWidgetItem.row()][ currentQTableWidgetItem.column()] = float( currentQTableWidgetItem.text())
class ToolBar(QWidget): mouseEntered = pyqtSignal() mouseLeft = pyqtSignal() toolChanged = pyqtSignal(str) primaryInkChanged = pyqtSignal(str) secondaryInkChanged = pyqtSignal(str) def __init__(self): super(ToolBar, self).__init__() self.setAttribute(Qt.WA_StaticContents) self.setAttribute(Qt.WA_NoSystemBackground) self.setFont(ResourcesCache.get("BigFont")) self._registeredTools = {} self._registeredInks = {} self._toolSlots = [] self._inkSlots = [] self._currentActiveToolSlot = None self._previousActiveToolSlot = None self._currentEditedInkSlot = None self._previousEditedInkSlot = None self._editMode = False self._backgroundColor = QColor(40, 40, 40) self._toolLabelColor = QColor(112, 231, 255) self._layout = QVBoxLayout() self._layout.setAlignment(Qt.AlignTop) self._layout.setContentsMargins(4, 4, 4, 4) top_layout = QHBoxLayout() self._layout.addLayout(top_layout) self._toolsLayout = QHBoxLayout() self._inksLayout = QHBoxLayout() self._toolsLayout.setContentsMargins(0, 0, 0, 0) self._toolsLayout.setAlignment(Qt.AlignLeft) self._inksLayout.setContentsMargins(0, 0, 0, 0) self._inksLayout.setAlignment(Qt.AlignRight) top_layout.addLayout(self._toolsLayout) top_layout.addLayout(self._inksLayout) self._toolsButtonGroup = QButtonGroup() self._toolsButtonGroup.buttonClicked.connect( self._on_tool_slot_triggered) self._inksButtonGroup = QButtonGroup() self._inksButtonGroup.setExclusive(False) self._inksButtonGroup.buttonClicked.connect( self._on_ink_slot_triggered) self.setLayout(self._layout) self._toolbarSubPanel = None self._toolsListWidget = None self._toolsOptionsPanel = None self._init_edit_panel() self._add_ink_slot(0) self._add_ink_slot(1) self.resize(0, 50) # ------------------------------------------------------------------------- def get_tool_by_name(self, name): return self._registeredTools[name] def register_tool(self, tool, is_default=None): if tool.name not in self._registeredTools: self._registeredTools[tool.name] = tool self._toolsListWidget.addItem(tool.name) if is_default is True: self._toolsListWidget.setCurrentRow(0) self._build_tool_options_pane(tool) if len(self._toolSlots) < 4: slot_index = self._add_tool_slot(is_default) self._assign_tool_to_slot(tool, slot_index) def register_ink(self, ink, slot): if not ink.name in self._registeredInks: self._registeredInks[ink.name] = ink self._inksListWidget.addItem(ink.name) self._build_ink_options_pane(ink) if self._inkSlots[slot]['id'] is None: self._assign_ink_to_slot(ink, slot) def switch_tool_slot(self, slot): self._previousActiveToolSlot = self._currentActiveToolSlot self._currentActiveToolSlot = slot if self._currentActiveToolSlot == self._previousActiveToolSlot: return tool_name = self._toolSlots[slot]['id'] self._toolSlots[slot]['button'].setChecked(True) self.toolChanged.emit(tool_name) self._select_tool_on_list(tool_name) # ------------------------------------------------------------------------- def _go_back_to_last_tool(self): self.switch_tool_slot(self._previousActiveToolSlot) def _add_tool_slot(self, selected=None): slot_button = QPushButton() slot_button.setCheckable(True) index = len(self._toolSlots) if selected is not None and selected is True: slot_button.setChecked(True) slot = {'id': None, 'button': slot_button} if selected: self._currentActiveToolSlot = index self._toolSlots.append(slot) self._toolsButtonGroup.addButton(slot_button, index) self._toolsLayout.addWidget(slot_button) return index def _add_ink_slot(self, slot_number): slot_button = QPushButton() slot_button.setFont(self.font()) slot_button.setStyleSheet( "border-color: rgb(56,56,56); background-color: rgb(17,17," "17); font-size: 12pt;") index = len(self._inkSlots) if slot_number == 0: icon = QIcon() icon.addPixmap(QPixmap(":/icons/ico_mouse_button1"), QIcon.Normal, QIcon.Off) slot_button.setIcon(icon) slot_button.setIconSize(QSize(18, 23)) elif slot_number == 1: icon = QIcon() icon.addPixmap(QPixmap(":/icons/ico_mouse_button2"), QIcon.Normal, QIcon.Off) slot_button.setIcon(icon) slot_button.setIconSize(QSize(18, 23)) slot = {'id': None, 'button': slot_button} self._inkSlots.append(slot) self._inksButtonGroup.addButton(slot_button) self._inksButtonGroup.setId(slot_button, index) self._inksLayout.addWidget(slot_button) return index def _assign_tool_to_slot(self, tool, slot): if slot < 0 or slot > len(self._toolSlots) - 1: raise Exception( '[ToolBar] > _assignToolToSlot : invalid slot parameter') self._toolSlots[slot]['id'] = tool.name icon = tool.icon if icon is not None: tool_button = self._toolSlots[slot]['button'] tool_button.setIcon(tool.icon) tool_button.setIconSize(QSize(24, 24)) def _assign_ink_to_slot(self, ink, slot): if slot != 0 and slot != 1: raise Exception( '[ToolBar] > _assignInkToSlot : invalid slot parameter') ink_name = ink.name self._inkSlots[slot]['id'] = ink_name self._inkSlots[slot]['button'].setText(ink_name) if slot == 0: self.primaryInkChanged.emit(ink_name) elif slot == 1: self.secondaryInkChanged.emit(ink_name) def _init_edit_panel(self): self._toolbarSubPanel = QStackedWidget() # 1. Initialize Tools Control Panel ----------------------------------- self._toolsListWidget = QListWidget() self._toolsListWidget.currentRowChanged.connect( lambda v: self._toolsOptionsPanel.setCurrentIndex(v)) self._toolsListWidget.setMaximumSize(QSize(150, 200)) self._toolsListWidget.itemClicked.connect( self._on_tool_list_item_clicked) # Tools Subpanel ------------------------------------------------------ tools_control_panel = QWidget() tools_control_panel_layout = QHBoxLayout() tools_control_panel.setLayout(tools_control_panel_layout) tools_control_panel_layout.setAlignment(Qt.AlignLeft) # Tools List ---------------------------------------------------------- tools_list_sublayout = QVBoxLayout() tools_list_sublayout.setAlignment(Qt.AlignTop) tools_list_sublayout.setContentsMargins(0, 0, 0, 0) tools_list_sublayout.addWidget(QLabel("Tools")) tools_list_sublayout.addWidget(self._toolsListWidget) tools_control_panel_layout.addLayout(tools_list_sublayout) # Tools Options ------------------------------------------------------- tools_options_sublayout = QVBoxLayout() tools_options_sublayout.setAlignment(Qt.AlignTop) tools_control_panel_layout.addLayout(tools_options_sublayout) self._toolsOptionsPanel = QStackedWidget() tools_options_sublayout.addWidget(QLabel("Tools Options")) tools_options_sublayout.addWidget(self._toolsOptionsPanel) self._toolbarSubPanel.addWidget(tools_control_panel) # 2. Initialize Inks Control Panel ------------------------------------ self._inksListWidget = QListWidget() self._inksListWidget.currentRowChanged.connect( lambda v: self._inksOptionsPanel.setCurrentIndex(v)) self._inksListWidget.setMaximumSize(QSize(150, 200)) self._inksListWidget.itemClicked.connect( self._on_ink_list_item_clicked) # Inks Subpanel ------------------------------------------------------- inks_control_panel = QWidget() inks_control_panel_layout = QHBoxLayout() inks_control_panel.setLayout(inks_control_panel_layout) inks_control_panel_layout.setAlignment(Qt.AlignLeft) # Inks List ----------------------------------------------------------- inks_list_sublayout = QVBoxLayout() inks_list_sublayout.setAlignment(Qt.AlignTop) inks_list_sublayout.setContentsMargins(0, 0, 0, 0) inks_list_sublayout.addWidget(QLabel("Inks")) inks_list_sublayout.addWidget(self._inksListWidget) inks_control_panel_layout.addLayout(inks_list_sublayout) # Inks Options -------------------------------------------------------- inks_options_sublayout = QVBoxLayout() inks_options_sublayout.setAlignment(Qt.AlignTop) inks_control_panel_layout.addLayout(inks_options_sublayout) self._inksOptionsPanel = QStackedWidget() inks_options_sublayout.addWidget(QLabel("Ink Options")) inks_options_sublayout.addWidget(self._inksOptionsPanel) self._toolbarSubPanel.addWidget(inks_control_panel) # --------------------------------------------------------------------- self._layout.addWidget(self._toolbarSubPanel) self._toolbarSubPanel.setVisible(False) def _build_tool_options_pane(self, tool): pane = QWidget() pane_layout = QVBoxLayout() pane_layout.setAlignment(Qt.AlignTop) pane.setLayout(pane_layout) for prop in tool.properties.values(): field_layout = QHBoxLayout() field_layout.addWidget(QLabel(prop.description)) prop_widget = prop.build_property_widget() field_layout.addWidget(prop_widget) pane_layout.addLayout(field_layout) self._toolsOptionsPanel.addWidget(pane) def _build_ink_options_pane(self, ink): pane = QWidget() pane_layout = QVBoxLayout() pane_layout.setAlignment(Qt.AlignTop) pane.setLayout(pane_layout) for prop in ink.properties.values(): field_layout = QHBoxLayout() field_layout.addWidget(QLabel(prop.description)) prop_widget = prop.build_property_widget() field_layout.addWidget(prop_widget) pane_layout.addLayout(field_layout) self._inksOptionsPanel.addWidget(pane) def _select_tool_on_list(self, tool_name): tool_list_item = \ self._toolsListWidget.findItems(tool_name, Qt.MatchExactly)[0] if tool_list_item is not None: self._toolsListWidget.setCurrentItem(tool_list_item) def _select_ink_on_list(self, ink_name): ink_list_item = \ self._inksListWidget.findItems(ink_name, Qt.MatchExactly)[0] if ink_list_item is not None: self._inksListWidget.setCurrentItem(ink_list_item) def _toggle_edit_mode(self): if not self._editMode: self._show_sub_panel() else: self._hide_sub_panel() self.update() def _show_sub_panel(self): self._editMode = True self.resize(self.width(), 300) self._toolbarSubPanel.setVisible(True) def _hide_sub_panel(self): self._editMode = False self.resize(self.width(), 50) self._toolbarSubPanel.setVisible(False) self._finish_ink_edit_mode() def _finish_ink_edit_mode(self): if self._currentEditedInkSlot is not None: self._inksButtonGroup.button(self._currentEditedInkSlot). \ setStyleSheet("border-color: rgb(56,56,56);") self._currentEditedInkSlot = None self._previousEditedInkSlot = None self._inksListWidget.setCurrentRow(0) self._toolbarSubPanel.setCurrentIndex(0) # ------------------------------------------------------------------------- def mousePressEvent(self, e): self._toggle_edit_mode() e.accept() def wheelEvent(self, e): e.accept() def enterEvent(self, e): self.mouseEntered.emit() self.setCursor(Qt.PointingHandCursor) def leaveEvent(self, e): self.mouseLeft.emit() def _on_tool_slot_triggered(self): self._toolbarSubPanel.setCurrentIndex(0) triggered_slot = self._toolsButtonGroup.checkedId() if self._currentEditedInkSlot is not None: self._finish_ink_edit_mode() self.switch_tool_slot(triggered_slot) self.update() def _on_ink_slot_triggered(self, slot_button): if not self._editMode: self._show_sub_panel() triggered_slot_id = self._inksButtonGroup.id(slot_button) if triggered_slot_id != self._currentEditedInkSlot: self._previousEditedInkSlot = self._currentEditedInkSlot self._currentEditedInkSlot = triggered_slot_id if self._previousEditedInkSlot is not None: self._inksButtonGroup. \ button(self._previousEditedInkSlot). \ setStyleSheet("border-color: rgb(56,56,56);") slot_button.setStyleSheet("border-color: rgb(255,0,0);") self._toolbarSubPanel.setCurrentIndex(1) ink_name = self._inkSlots[triggered_slot_id]['id'] self._select_ink_on_list(ink_name) if triggered_slot_id == 0: self.primaryInkChanged.emit(ink_name) elif triggered_slot_id == 1: self.secondaryInkChanged.emit(ink_name) else: self._hide_sub_panel() def _on_tool_list_item_clicked(self, new_item): new_item_name = new_item.text() self._assign_tool_to_slot(self.get_tool_by_name(new_item_name), self._currentActiveToolSlot) self.toolChanged.emit(new_item_name) self._toolbarSubPanel.update() def _on_ink_list_item_clicked(self, item): item_name = item.text() ink = self._registeredInks[item_name] if ink is not None: self._assign_ink_to_slot(ink, self._currentEditedInkSlot)
class MultplayerTournamentItem(): def __init__(self, y_pos, x_pos, startCheck: int): tb_x_pos = x_pos cb_x_pos = x_pos + 300 cb_x_step = 75 self.textbox = QLineEdit() self.textbox.move(tb_x_pos, y_pos) self.textbox.resize(280, 40) font1 = self.textbox.font() font1.setPointSize(20) self.textbox.setFont(font1) self.buttonGroup = QButtonGroup() self.radiobutton1 = QRadioButton("Gray") self.radiobutton2 = QRadioButton("Red") self.radiobutton3 = QRadioButton("Yellow") self.radiobutton4 = QRadioButton("Green") font = QFont() font.setStyleHint(QFont.Helvetica) font.setPointSize(13) font.setBold(True) self.radiobutton1.setFont(font) self.radiobutton2.setFont(font) self.radiobutton3.setFont(font) self.radiobutton4.setFont(font) self.buttonGroup.addButton(self.radiobutton1) self.buttonGroup.addButton(self.radiobutton2) self.buttonGroup.addButton(self.radiobutton3) self.buttonGroup.addButton(self.radiobutton4) self.buttonGroup.setId(self.radiobutton1, 1) self.buttonGroup.setId(self.radiobutton2, 2) self.buttonGroup.setId(self.radiobutton3, 3) self.buttonGroup.setId(self.radiobutton4, 4) if startCheck is 1: self.radiobutton1.setChecked(True) elif startCheck is 2: self.radiobutton2.setChecked(True) elif startCheck is 3: self.radiobutton3.setChecked(True) else: self.radiobutton4.setChecked(True) y_plus = 7 self.radiobutton1.move(cb_x_pos, y_pos + y_plus) self.radiobutton2.move(cb_x_pos + cb_x_step, y_pos + y_plus) self.radiobutton3.move(cb_x_pos + cb_x_step * 2, y_pos + y_plus) self.radiobutton4.move(cb_x_pos + cb_x_step * 3, y_pos + y_plus) def hideAllWidgets(self): self.textbox.hide() self.radiobutton1.hide() self.radiobutton2.hide() self.radiobutton3.hide() self.radiobutton4.hide() def showAllWidgets(self): self.textbox.show()
class ConfigBox(QGroupBox): modified = pyqtSignal() def __init__(self): super(ConfigBox, self).__init__() self._state_engine_option: List[ConfigParam] = [] self._state_use_encryption = True self._state_engine_option_holder: List[Union[QButtonGroup, QDoubleSpinBox]] = [] self._setup_ui() def _setup_ui(self): self.setTitle('Options') self._main_layout = QFormLayout() # Label self._encrypt_option_label = QLabel() self._encrypt_option_label.setText('Encryption') self._encrypt_password_label = QLabel() self._encrypt_password_label.setText('Key') # Encryption radio self._encrypt_option_group = QButtonGroup() self._encrypt_option_layout = QHBoxLayout() self._encrypt_option = QRadioButton() self._encrypt_option.setText('Enabled') self._encrypt_option.setChecked(True) self._encrypt_option.clicked.connect(self._on_radio_selected) self._no_encrypt_option = QRadioButton() self._no_encrypt_option.setText('Disabled') self._no_encrypt_option.clicked.connect(self._on_radio_selected) self._encrypt_option_group.addButton(self._encrypt_option) self._encrypt_option_group.setId(self._encrypt_option, 1) self._encrypt_option_layout.addWidget(self._encrypt_option) self._encrypt_option_group.addButton(self._no_encrypt_option) self._encrypt_option_group.setId(self._no_encrypt_option, 0) self._encrypt_option_layout.addWidget(self._no_encrypt_option) self._encrypt_option_layout.addStretch() # Encryption password self._encrypt_password = QLineEdit() self._encrypt_password.setMaxLength(25) self._encrypt_password.setText(StringUtil.generate_random_string(6)) # Engine options self._engine_option_layout = QVBoxLayout() # Add to layout self._main_layout.addRow(self._encrypt_option_label, self._encrypt_option_layout) self._main_layout.addRow(self._encrypt_password_label, self._encrypt_password) self.setLayout(self._main_layout) def disable_encrypt_option(self): self._encrypt_option_layout.removeWidget(self._encrypt_option) self._encrypt_option_layout.removeWidget(self._no_encrypt_option) label = QLabel() label.setText('Will be determined by file metadata') self._encrypt_option_layout.addWidget(label) def set_engine_option(self, engine_option: List[ConfigParam]): row_count = self._main_layout.rowCount() for i in range(row_count - 1, 1, -1): self._main_layout.removeRow(i) if len(engine_option) == 0: return self._state_engine_option = engine_option self._state_engine_option_holder.clear() for param in engine_option: engine_option_label = QLabel() engine_option_label.setText(param.title) if param.config_type == ConfigType.RADIO: assert isinstance(param, RadioParam) option_group = QButtonGroup() button_layout = QHBoxLayout() for idx, (key, value) in enumerate(param.options.items()): radio_btn = QRadioButton() radio_btn.setText(value) if idx == 0: radio_btn.setChecked(True) radio_btn.clicked.connect(lambda: self.modified.emit()) option_group.addButton(radio_btn) option_group.setId(radio_btn, idx) button_layout.addWidget(radio_btn) self._main_layout.addRow(engine_option_label, button_layout) self._state_engine_option_holder.append(option_group) elif param.config_type == ConfigType.FLOAT: assert isinstance(param, FloatParam) spinbox = QDoubleSpinBox() spinbox.setValue(param.default) spinbox.setMinimum(0) spinbox.setSingleStep(param.step) spinbox.valueChanged.connect(lambda: self.modified.emit()) self._state_engine_option_holder.append(spinbox) self._main_layout.addRow(engine_option_label, spinbox) @property def config(self) -> Tuple[str, List[Union[str, float, bool]]]: encryption_key = self._encrypt_password.text() engine_param = [self._state_use_encryption] for idx, param in enumerate(self._state_engine_option): holder = self._state_engine_option_holder[idx] if param.config_type == ConfigType.FLOAT: assert isinstance(holder, QDoubleSpinBox) engine_param.append(holder.value()) else: assert isinstance(holder, QButtonGroup) assert isinstance(param, RadioParam) option = param.options engine_param.append(list(option.keys())[holder.checkedId()]) return encryption_key, engine_param def _on_radio_selected(self): # self._encrypt_password.setDisabled(self._encrypt_option_group.checkedId() == 0) self._state_use_encryption = self._encrypt_option_group.checkedId( ) == 1
def request_trezor_init_settings(self, wizard, method, device_id): vbox = QVBoxLayout() next_enabled = True devmgr = self.device_manager() client = devmgr.client_by_id(device_id) if not client: raise Exception(_("The device was disconnected.")) model = client.get_trezor_model() fw_version = client.client.version capabilities = client.client.features.capabilities have_shamir = Capability.Shamir in capabilities # label label = QLabel(_("Enter a label to name your device:")) name = QLineEdit() hl = QHBoxLayout() hl.addWidget(label) hl.addWidget(name) hl.addStretch(1) vbox.addLayout(hl) # Backup type gb_backuptype = QGroupBox() hbox_backuptype = QHBoxLayout() gb_backuptype.setLayout(hbox_backuptype) vbox.addWidget(gb_backuptype) gb_backuptype.setTitle(_('Select backup type:')) bg_backuptype = QButtonGroup() rb_single = QRadioButton(gb_backuptype) rb_single.setText(_('Single seed (BIP39)')) bg_backuptype.addButton(rb_single) bg_backuptype.setId(rb_single, BackupType.Bip39) hbox_backuptype.addWidget(rb_single) rb_single.setChecked(True) rb_shamir = QRadioButton(gb_backuptype) rb_shamir.setText(_('Shamir')) bg_backuptype.addButton(rb_shamir) bg_backuptype.setId(rb_shamir, BackupType.Slip39_Basic) hbox_backuptype.addWidget(rb_shamir) rb_shamir.setEnabled(Capability.Shamir in capabilities) rb_shamir.setVisible(False) # visible with "expert settings" rb_shamir_groups = QRadioButton(gb_backuptype) rb_shamir_groups.setText(_('Super Shamir')) bg_backuptype.addButton(rb_shamir_groups) bg_backuptype.setId(rb_shamir_groups, BackupType.Slip39_Advanced) hbox_backuptype.addWidget(rb_shamir_groups) rb_shamir_groups.setEnabled(Capability.ShamirGroups in capabilities) rb_shamir_groups.setVisible(False) # visible with "expert settings" # word count word_count_buttons = {} gb_numwords = QGroupBox() hbox1 = QHBoxLayout() gb_numwords.setLayout(hbox1) vbox.addWidget(gb_numwords) gb_numwords.setTitle(_("Select seed/share length:")) bg_numwords = QButtonGroup() for count in (12, 18, 20, 24, 33): rb = QRadioButton(gb_numwords) word_count_buttons[count] = rb rb.setText(_("{:d} words").format(count)) bg_numwords.addButton(rb) bg_numwords.setId(rb, count) hbox1.addWidget(rb) rb.setChecked(True) def configure_word_counts(): if model == "1": checked_wordcount = 24 else: checked_wordcount = 12 if method == TIM_RECOVER: if have_shamir: valid_word_counts = (12, 18, 20, 24, 33) else: valid_word_counts = (12, 18, 24) elif rb_single.isChecked(): valid_word_counts = (12, 18, 24) gb_numwords.setTitle(_('Select seed length:')) else: valid_word_counts = (20, 33) checked_wordcount = 20 gb_numwords.setTitle(_('Select share length:')) word_count_buttons[checked_wordcount].setChecked(True) for c, btn in word_count_buttons.items(): btn.setVisible(c in valid_word_counts) bg_backuptype.buttonClicked.connect(configure_word_counts) configure_word_counts() # set up conditional visibility: # 1. backup_type is only visible when creating new seed gb_backuptype.setVisible(method == TIM_NEW) # 2. word_count is not visible when recovering on TT if method == TIM_RECOVER and model != "1": gb_numwords.setVisible(False) # PIN cb_pin = QCheckBox(_('Enable PIN protection')) cb_pin.setChecked(True) vbox.addWidget(WWLabel(RECOMMEND_PIN)) vbox.addWidget(cb_pin) # "expert settings" button expert_vbox = QVBoxLayout() expert_widget = QWidget() expert_widget.setLayout(expert_vbox) expert_widget.setVisible(False) expert_button = QPushButton(_("Show expert settings")) def show_expert_settings(): expert_button.setVisible(False) expert_widget.setVisible(True) rb_shamir.setVisible(True) rb_shamir_groups.setVisible(True) expert_button.clicked.connect(show_expert_settings) vbox.addWidget(expert_button) # passphrase passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT) passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN) passphrase_warning.setStyleSheet("color: red") cb_phrase = QCheckBox(_('Enable passphrases')) cb_phrase.setChecked(False) expert_vbox.addWidget(passphrase_msg) expert_vbox.addWidget(passphrase_warning) expert_vbox.addWidget(cb_phrase) # ask for recovery type (random word order OR matrix) bg_rectype = None if method == TIM_RECOVER and model == '1': gb_rectype = QGroupBox() hbox_rectype = QHBoxLayout() gb_rectype.setLayout(hbox_rectype) expert_vbox.addWidget(gb_rectype) gb_rectype.setTitle(_("Select recovery type:")) bg_rectype = QButtonGroup() rb1 = QRadioButton(gb_rectype) rb1.setText(_('Scrambled words')) bg_rectype.addButton(rb1) bg_rectype.setId(rb1, RecoveryDeviceType.ScrambledWords) hbox_rectype.addWidget(rb1) rb1.setChecked(True) rb2 = QRadioButton(gb_rectype) rb2.setText(_('Matrix')) bg_rectype.addButton(rb2) bg_rectype.setId(rb2, RecoveryDeviceType.Matrix) hbox_rectype.addWidget(rb2) # no backup cb_no_backup = None if method == TIM_NEW: cb_no_backup = QCheckBox(f'''{_('Enable seedless mode')}''') cb_no_backup.setChecked(False) if (model == '1' and fw_version >= (1, 7, 1) or model == 'T' and fw_version >= (2, 0, 9)): cb_no_backup.setToolTip(SEEDLESS_MODE_WARNING) else: cb_no_backup.setEnabled(False) cb_no_backup.setToolTip(_('Firmware version too old.')) expert_vbox.addWidget(cb_no_backup) vbox.addWidget(expert_widget) wizard.exec_layout(vbox, next_enabled=next_enabled) return TrezorInitSettings( word_count=bg_numwords.checkedId(), label=name.text(), pin_enabled=cb_pin.isChecked(), passphrase_enabled=cb_phrase.isChecked(), recovery_type=bg_rectype.checkedId() if bg_rectype else None, backup_type=bg_backuptype.checkedId(), no_backup=cb_no_backup.isChecked() if cb_no_backup else False, )
def request_trezor_init_settings(self, wizard, method, device): vbox = QVBoxLayout() next_enabled = True label = QLabel(_("Enter a label to name your device:")) name = QLineEdit() hl = QHBoxLayout() hl.addWidget(label) hl.addWidget(name) hl.addStretch(1) vbox.addLayout(hl) def clean_text(widget): text = widget.toPlainText().strip() return ' '.join(text.split()) if method in [TIM_NEW, TIM_RECOVER]: gb = QGroupBox() hbox1 = QHBoxLayout() gb.setLayout(hbox1) # KeepKey recovery doesn't need a word count if method == TIM_NEW: vbox.addWidget(gb) gb.setTitle(_("Select your seed length:")) bg = QButtonGroup() for i, count in enumerate([12, 18, 24]): rb = QRadioButton(gb) rb.setText(_("{} words").format(count)) bg.addButton(rb) bg.setId(rb, i) hbox1.addWidget(rb) rb.setChecked(True) cb_pin = QCheckBox(_('Enable PIN protection')) cb_pin.setChecked(True) else: text = QTextEdit() text.setMaximumHeight(60) if method == TIM_MNEMONIC: msg = _("Enter your BIP39 mnemonic:") else: msg = _("Enter the master private key beginning with xprv:") def set_enabled(): from electrum.bip32 import is_xprv wizard.next_button.setEnabled(is_xprv(clean_text(text))) text.textChanged.connect(set_enabled) next_enabled = False vbox.addWidget(QLabel(msg)) vbox.addWidget(text) pin = QLineEdit() pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,9}'))) pin.setMaximumWidth(100) hbox_pin = QHBoxLayout() hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):"))) hbox_pin.addWidget(pin) hbox_pin.addStretch(1) if method in [TIM_NEW, TIM_RECOVER]: vbox.addWidget(WWLabel(RECOMMEND_PIN)) vbox.addWidget(cb_pin) else: vbox.addLayout(hbox_pin) passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT) passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN) passphrase_warning.setStyleSheet("color: red") cb_phrase = QCheckBox(_('Enable passphrases')) cb_phrase.setChecked(False) vbox.addWidget(passphrase_msg) vbox.addWidget(passphrase_warning) vbox.addWidget(cb_phrase) wizard.exec_layout(vbox, next_enabled=next_enabled) if method in [TIM_NEW, TIM_RECOVER]: item = bg.checkedId() pin = cb_pin.isChecked() else: item = ' '.join(str(clean_text(text)).split()) pin = str(pin.text()) return (item, name.text(), pin, cb_phrase.isChecked())
class FontCommandWidget(QScrollArea): """Displays and manipulates a font setting command.""" # Store templates as class variablese lilypond_template = """ #(define fonts (set-global-fonts <<<fontdefinitions>>> #:factor (/ staff-height pt 20) ))""" lilypond_paper_block = """\\paper { <<<command>>> }""" oll_template = '\\useNotationFont {}"{}"' oll_properties = """\\with { <<<properties>>> } """ def __init__(self, parent): super(FontCommandWidget, self).__init__(parent) self._cmd = {'lily': '', 'oll': ''} self._full_cmd = {'lily': '', 'oll': ''} self.approach = 'lily' self.font_labels = {} mainWidget = QWidget() self.setWidgetResizable(True) self.setWidget(mainWidget) self.setFrameShape(QScrollArea.NoFrame) layout = QVBoxLayout() mainWidget.setLayout(layout) col_layout = QHBoxLayout() layout.addLayout(col_layout) layout.addStretch() # Left column holding the options self.option_widget = QWidget() opt_layout = QVBoxLayout(margin=0) self.option_widget.setLayout(opt_layout) col_layout.addWidget(self.option_widget) # TextEdit to display the generated command self.command_edit = ce = QTextEdit() ce.setReadOnly(True) col_layout.addWidget(self.command_edit) # Which text font families to integrate? self.family_group = QGroupBox() opt_layout.addWidget(self.family_group) family_layout = QGridLayout() self.family_group.setLayout(family_layout) self.cb_roman = QCheckBox() self.font_labels['roman'] = QLabel(parent.selected_font('roman')) family_layout.addWidget(self.cb_roman, 0, 0) family_layout.addWidget(self.font_labels['roman'], 0, 1) self.cb_sans = QCheckBox() self.font_labels['sans'] = QLabel(parent.selected_font('sans')) family_layout.addWidget(self.cb_sans, 1, 0) family_layout.addWidget(self.font_labels['sans'], 1, 1) self.cb_typewriter = QCheckBox() self.font_labels['typewriter'] = QLabel( parent.selected_font('typewriter')) family_layout.addWidget(self.cb_typewriter, 2, 0) family_layout.addWidget(self.font_labels['typewriter'], 2, 1) # Choice between traditional and openLilyLib approach self.approach_group = QGroupBox() approach_layout = QVBoxLayout() self.approach_group.setLayout(approach_layout) self.approach_tab = QTabWidget() approach_layout.addWidget(self.approach_tab) opt_layout.addWidget(self.approach_group) self.trad_widget = QWidget() trad_layout = QVBoxLayout() self.trad_widget.setLayout(trad_layout) self.approach_tab.addTab(self.trad_widget, "") self.oll_widget = QWidget() oll_layout = QVBoxLayout() self.oll_widget.setLayout(oll_layout) self.approach_tab.addTab(self.oll_widget, "") # Configure traditional approach self.cb_music = QCheckBox() self.font_labels['music'] = QLabel(parent.selected_font('music')) trad_music_layout = QHBoxLayout() trad_music_layout.addWidget(self.cb_music) trad_music_layout.addWidget(self.font_labels['music']) trad_layout.addLayout(trad_music_layout) self.cb_paper_block = QCheckBox() trad_layout.addWidget(self.cb_paper_block) trad_layout.addStretch() # Configure openLilyLib approach self.cb_oll_music = QCheckBox() self.cb_oll_music.setChecked(True) self.cb_oll_music.setEnabled(False) self.font_labels['oll_music'] = QLabel(parent.selected_font('music')) oll_music_layout = QHBoxLayout() oll_music_layout.addWidget(self.cb_oll_music) oll_music_layout.addWidget(self.font_labels['oll_music']) oll_layout.addLayout(oll_music_layout) self.cb_oll = QCheckBox() oll_layout.addWidget(self.cb_oll) self.cb_loadpackage = QCheckBox() oll_layout.addWidget(self.cb_loadpackage) self.cb_extensions = QCheckBox() oll_layout.addWidget(self.cb_extensions) # Configure handling of stylesheet self.stylesheet_group = QGroupBox() self.stylesheet_buttons = QButtonGroup() oll_layout.addWidget(self.stylesheet_group) stylesheet_layout = QVBoxLayout() self.stylesheet_group.setLayout(stylesheet_layout) self.style_buttons = [QRadioButton() for i in range(3)] for i in range(3): b = self.style_buttons[i] stylesheet_layout.addWidget(b) self.stylesheet_buttons.addButton(b) self.stylesheet_buttons.setId(b, i) self.le_stylesheet = QLineEdit() stylesheet_layout.addWidget(self.le_stylesheet) oll_layout.addStretch() # enable line edit when custom stylesheet is selected self.stylesheet_buttons.buttonClicked.connect( lambda: self.le_stylesheet.setEnabled(self.stylesheet_buttons. checkedId() == 2)) self.loadSettings() self.window().finished.connect(self.saveSettings) # Connect widgets that trigger re-generation of the command # Map widget base classes to signal names signal_map = { QAbstractButton: 'toggled', QButtonGroup: 'buttonClicked', QTabWidget: 'currentChanged', QLineEdit: 'editingFinished' } trigger_widgets = [ self.cb_roman, self.cb_sans, self.cb_typewriter, self.cb_music, self.cb_paper_block, ] trigger_widgets.extend([ self.approach_tab, self.cb_oll, self.cb_loadpackage, self.cb_extensions, self.stylesheet_buttons, self.le_stylesheet ]) for w in trigger_widgets: # For the current widget determine a supported base class # and connect the appropriate signal. # NOTE: When a new widget is added to the list it has to be # ensured it has a supported base class. for base_class in signal_map: if isinstance(w, base_class): signal = getattr(w, signal_map[base_class]) signal.connect(self.invalidate_command) break app.translateUI(self) def translateUI(self): self.family_group.setTitle(_("Set font families")) self.cb_roman.setText(_("Roman")) self.cb_sans.setText(_("Sans")) self.cb_typewriter.setText(_("Typewriter")) self.approach_group.setTitle(_("Configure command generation")) self.approach_tab.setTabText(0, _("Traditional")) self.approach_tab.setTabToolTip( 0, _("Specify fonts using the setting in a \\paper block.")) self.approach_tab.setTabText(1, _("openLilyLib")) self.approach_tab.setTabToolTip( 1, _("Specify fonts using the setting using openLilyLib.\n" + "NOTE: This requires openLilyLib (oll-core)\n" + "and the 'notation-fonts' openLilyLib package.")) self.cb_music.setText(_("Set music font")) self.cb_paper_block.setText(_("Complete \\paper block")) self.cb_paper_block.setToolTip( _("Wrap setting in a complete \\paper block.\n" + "If unchecked generate the raw font setting command.")) self.cb_oll_music.setText(_("Set music font")) self.cb_oll_music.setToolTip( _("Specify the music font.\n" + "This is a reminder only and can not be unckecked " + "because the openLilyLib approach necessarily sets " + "the music font.")) self.cb_oll.setText(_("Load openLilyLib")) self.cb_oll.setToolTip( _("Load openLilyLib (oll-core) explicitly.\n" + "Unckeck if oll-core is already loaded elsewhere.")) self.cb_loadpackage.setText(_("Load notation-fonts package")) self.cb_loadpackage.setToolTip( _("Load the notation-fonts package explicitly.\n" + "Unckeck if it is already loaded elsewhere.")) self.cb_extensions.setText(_("Load font extensions (if available)")) self.cb_extensions.setToolTip( _("Ask for loading font extensions.\n" + "Note that *some* fonts provide additional features\n" + "(e.g. glyphs) that can be made available through an\n" + "extension stylesheet if provided.")) self.stylesheet_group.setTitle(_("Font stylesheet")) self.stylesheet_group.setToolTip( _("Select alternative stylesheet.\n" + "Fonts natively supported by the notation-fonts\n" + "package provide a default stylesheet to adjust\n" + "LilyPond's visuals (e.g. line thicknesses) to the\n" + "characteristic of the music font.\n" + "Check 'No stylesheet' to avoid a preconfigured\n" + "stylesheet to customize the appearance manually,\n" + "or check 'Custom stylesheet' to load another stylesheet\n" + "in LilyPond's search path.")) self.style_buttons[0].setText(_("Default stylesheet")) self.style_buttons[1].setText(_("No stylesheet")) self.style_buttons[2].setText(_("Custom stylesheet")) def loadSettings(self): s = QSettings() s.beginGroup('document-fonts-dialog') self.cb_roman.setChecked(s.value('set-roman', False, bool)) self.cb_sans.setChecked(s.value('set-sans', False, bool)) self.cb_roman.setChecked(s.value('set-roman', False, bool)) self.cb_music.setChecked(s.value('set-music', True, bool)) self.approach_tab.setCurrentIndex(s.value('approach-index', 0, int)) self.cb_paper_block.setChecked(s.value('set-paper-block', True, bool)) self.cb_oll.setChecked(s.value('load-oll', True, bool)) self.cb_loadpackage.setChecked(s.value('load-package', True, bool)) self.cb_extensions.setChecked(s.value('font-extensions', False, bool)) style_type = s.value('style-type', 0, int) self.style_buttons[style_type].setChecked(True) self.le_stylesheet.setText(s.value('font-stylesheet', '', str)) self.le_stylesheet.setEnabled(self.style_buttons[2].isChecked()) def saveSettings(self): s = QSettings() s.beginGroup('document-fonts-dialog') s.setValue('set-roman', self.cb_roman.isChecked()) s.setValue('set-sans', self.cb_sans.isChecked()) s.setValue('set-roman', self.cb_roman.isChecked()) s.setValue('set-paper-block', self.cb_paper_block.isChecked()) s.setValue('approach-index', self.approach_tab.currentIndex()) s.setValue('set-music', self.cb_music.isChecked()) s.setValue('load-oll', self.cb_oll.isChecked()) s.setValue('load-package', self.cb_loadpackage.isChecked()) s.setValue('font-extensions', self.cb_extensions.isChecked()) s.setValue('style-type', self.stylesheet_buttons.checkedId()) s.setValue('font-stylesheet', self.le_stylesheet.text()) def command(self, approach='lily'): """Return the command as shown in the Font Command tab.""" if not self._cmd[approach]: self.invalidate_command() return self._cmd[approach] def generate_lily_command(self): """ Generate a font setting command in the traditional LilyPond way using #(define fonts ...) in a \\paper block. Returns a tuple with two versions of the command: - command as shown in the Font Command tab => with various filters applied - "full" command without the filters. => as used in the Font Preview, and maybe the Document wizard """ # Definitions are initially handled as string lists, # and later joined to multiline strings. fontdefs = [] full_fontdefs = [] template = self.lilypond_template def add_font_def(k, name, checked): """ Add a font entry to the commands when applicable. """ font_entry = ' #:{} "{}"'.format(k, name) if checked: fontdefs.append(font_entry) full_fontdefs.append(font_entry) def font_defs(): """Compose the font definitions list.""" add_font_def('music', self.window().selected_font('music'), self.cb_music.isChecked()) add_font_def('brace', self.window().selected_font('brace'), self.cb_music.isChecked()) add_font_def('roman', self.window().selected_font('roman'), self.cb_roman.isChecked()) add_font_def('sans', self.window().selected_font('sans'), self.cb_sans.isChecked()) add_font_def('typewriter', self.window().selected_font('typewriter'), self.cb_typewriter.isChecked()) return "\n".join(fontdefs), "\n".join(full_fontdefs) fontdefs, full_fontdefs = font_defs() cmd = template.replace('<<<fontdefinitions>>>', fontdefs) full_cmd = template.replace('<<<fontdefinitions>>>', full_fontdefs) if self.cb_paper_block.isChecked(): cmd = self.lilypond_paper_block.replace('<<<command>>>', cmd) full_cmd = self.lilypond_paper_block.replace('<<<command>>>', full_cmd) return cmd, full_cmd def generate_oll_command(self): """ Generate a font setting command using openLilyLib's notation-fonts package. Returns a tuple with two versions of the command: - command as shown in the Font Command tab => with various filters applied - "full" command without the filters. => as used in the Font Preview, and maybe the Document wizard """ # Handled initially as string lists, later joined to multiline strings cmd = [] full_cmd = [] properties = [] full_properties = [] def add_property(k, v, checked, force=True): """ Add a property entry to the full command and conditionally to the regular command. """ property = ' {} = {}'.format(k, v) if checked: properties.append(property) if checked or force: full_properties.append(property) # Load openLilyLib oll_include = '\\include "oll-core/package.ily"' full_cmd.append(oll_include) if self.cb_oll.isChecked(): cmd.append(oll_include) # Load the notation-fonts package package_include = '\\loadPackage notation-fonts' full_cmd.append(package_include) if self.cb_loadpackage.isChecked(): cmd.append(package_include) # TODO: Support independent explicit brace font add_property('brace', '"{}"'.format(self.window().selected_font('brace')), False) # Specify text fonts add_property('roman', '"{}"'.format(self.window().selected_font('roman')), self.cb_roman.isChecked(), force=True) add_property('sans', '"{}"'.format(self.window().selected_font('sans')), self.cb_sans.isChecked(), force=True) add_property('typewriter', '"{}"'.format(self.window().selected_font('typewriter')), self.cb_typewriter.isChecked(), force=True) # Optionally load font extensions if self.cb_extensions.isChecked(): add_property('extensions', '##t', True) # Handle font stylesheet style_type = self.stylesheet_buttons.checkedId() # style_type == 0 => default stylesheet, doesn't have to be written if style_type == 1: # Don't use a stylesheet add_property('style', 'none', True) elif style_type == 2: # Use custom stylesheet (must be findable of course) add_property('style', '"{}"'.format(self.le_stylesheet.text()), True) # Generate the \with clause ... full_properties = self.oll_properties.replace( '<<<properties>>>', '\n'.join(full_properties)) # ... conditionally for the regular command if properties: properties = self.oll_properties.replace('<<<properties>>>', '\n'.join(properties)) else: properties = '' # Inject properties in the \useNotationFont command cmd.append( self.oll_template.format(properties, self.window().selected_font('music'))) full_cmd.append( self.oll_template.format(full_properties, self.window().selected_font('music'))) # Return regular and full command return "\n".join(cmd), "\n".join(full_cmd) def invalidate_command(self, _=None): """ Regenerate both 'lily' and 'oll' versions of the regular and full font commands. Display the regular command in the textedit and trigger showing the sample in the music font tab. """ self._cmd['lily'], self._full_cmd['lily'] = self.generate_lily_command( ) self._cmd['oll'], self._full_cmd['oll'] = (self.generate_oll_command()) self.approach = ('lily' if self.approach_tab.currentIndex() == 0 else 'oll') display_cmd = self._cmd[self.approach] self.command_edit.setPlainText(display_cmd) highlighter.highlight(self.command_edit.document()) for k in self.font_labels: font_key = 'music' if k == 'oll_music' else k self.font_labels[k].setText(self.window().selected_font(font_key)) self.window().show_sample() def full_cmd(self, approach='lily'): """Return the (cached) full command for the requested approach.""" if not self._full_cmd[approach]: self.invalidate_command() return self._full_cmd[approach]
class DataCheck(Content): def __init__(self, parent=None, button_func=None, params=None): super().__init__(parent, 'Data check', params) self.button_func = button_func path = os.path.abspath(os.path.dirname(__file__)) + '/static/' # nr = min(5, data.shape[0]) nr = len(self.params.data5) if params.lang == 'jp': text = ('データの読み込み結果(先頭{n}行)を以下に示します.\n' 'データを正しく読み込めていることを確認してください.'.format(n=nr)) self.set_paragraph( 'データ読み込み結果の確認', text=text) else: text = ('First {n} rows of your data are shown below.\n' 'Confirm that the data was read correctly.'.format(n=nr)) self.set_paragraph( 'Check data', text=text) table = NonScrollTable(self.inner) table.setRowCount(nr) table.setColumnCount(len(self.params.columns)) table.setHorizontalHeaderLabels(self.params.columns) for r in range(nr): for c in range(len(self.params.columns)): item = QTableWidgetItem(str(self.params.data5.iat[r, c])) item.setFlags(Qt.ItemIsEnabled) table.setItem(r, c, item) table.setNonScroll() self.vbox.addWidget(table) # Text for type checking and objective variable setting path1 = path + 'categorical' text = self.get_text(path1) if self.params.lang == 'en': self.set_paragraph( 'Check type of variables and set objective variable', text=text) else: self.set_paragraph('変数タイプの確認と目的変数の設定', text=text) # htable = QTableWidget(self.inner) htable = NonScrollTable(self.inner) htable.setRowCount(len(self.params.columns)) htable.setColumnCount(4) htable.setHorizontalHeaderLabels( ['columns', 'categorical', 'numerical', 'target']) self.lst_cat = [] self.lst_num = [] self.lst_obj = [] self.obj_group = QButtonGroup(self.inner) for c in range(len(self.params.columns)): # col 1 item = QTableWidgetItem(self.params.columns[c]) item.setFlags(Qt.ItemIsEnabled) htable.setItem(c, 0, item) group = QButtonGroup(self.inner) # col 2 htable.setCellWidget( c, 1, self.__make_cell(c, 'cat', self.params.col_types[c], self.params.col_types_def[c])) group.addButton(self.lst_cat[-1]) # col 3 htable.setCellWidget( c, 2, self.__make_cell(c, 'num', self.params.col_types[c], self.params.col_types_def[c])) group.addButton(self.lst_num[-1]) # col 4 htable.setCellWidget( c, 3, self.__make_cell(c, 'obj', self.params.col_types[c], self.params.col_types_def[c])) self.obj_group.addButton(self.lst_obj[-1]) self.obj_group.setId(self.lst_obj[-1], c) htable.setNonScroll() self.vbox.addWidget(htable) if self.params.lang == 'jp': self.txt_cnf = ('<font color="red">目的変数を1つ選択し,' 'targetの列にチェックをいれてください。') if self.params.task.lower() == 'classification': self.txt_cnf += '<br>目的変数はカテゴリ変数である必要があります。</font>' else: self.txt_cnf += '<br>目的変数は量的変数である必要があります。</font>' else: self.txt_cnf = ('<font color="red">Select one variable as target variable,' 'then set the column of "target" of the variable checked.') if self.params.task.lower() == 'classification': self.txt_cnf += '<br>Target variable must be a categorical variable.</font>' else: self.txt_cnf += '<br>Target variable must be a numerical variable.</font>' self.lbl_cnf = QLabel(self.txt_cnf, self.inner) self.vbox.addWidget(self.lbl_cnf) self.vbox.addStretch(1) self.btn = QPushButton('Next', self.inner) self.btn.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};') if self.params.lang == 'en': self.btn.clicked.connect(lambda: self.button_func('Overfitting')) else: self.btn.clicked.connect(lambda: self.button_func('過学習')) if self.obj_group.checkedButton() is None: self.btn.setEnabled(False) else: self.btn.setEnabled(True) self.vbox.addWidget(self.btn) def __make_cell(self, c, name, col_type, col_type_def): cell = QWidget(self.inner) rbtn = QRadioButton('', cell) rbtn.toggled.connect(lambda: self.rbtn_clicked(name + '_' + str(c))) hbl = QHBoxLayout(cell) hbl.addWidget(rbtn) hbl.setContentsMargins(0, 0, 0, 0) hbl.setAlignment(Qt.AlignCenter) cell.setLayout(hbl) if name == 'cat': if col_type == 'object': rbtn.setChecked(True) self.lst_cat.append(rbtn) elif name == 'num': if col_type != 'object': rbtn.setChecked(True) if col_type_def == 'object': rbtn.setEnabled(False) self.lst_num.append(rbtn) elif name == 'obj': if col_type == 'object' and self.params.task == 'Regression': rbtn.setEnabled(False) elif col_type != 'object' and self.params.task == 'Classification': rbtn.setEnabled(False) if self.params.columns[c] == self.params.objective: rbtn.setChecked(True) self.lst_obj.append(rbtn) return cell def rbtn_clicked(self, text): name, idx = text.split('_') idx = int(idx) if len(self.lst_obj) <= idx: return if self.lst_num[idx].isChecked(): if self.params.task == 'Classification': self.obj_group.setExclusive(False) self.lst_obj[idx].setChecked(False) self.obj_group.setExclusive(True) self.lst_obj[idx].setEnabled(False) elif self.params.task == 'Regression': self.lst_obj[idx].setEnabled(True) self.params.col_types[idx] = self.params.col_types_def[idx] elif self.lst_cat[idx].isChecked(): if self.params.task == 'Classification': self.lst_obj[idx].setEnabled(True) elif self.params.task == 'Regression': self.obj_group.setExclusive(False) self.lst_obj[idx].setChecked(False) self.obj_group.setExclusive(True) self.lst_obj[idx].setEnabled(False) self.params.col_types[idx] = 'object' if self.obj_group.checkedButton() is None: self.params.objective = None self.lbl_cnf.setText(self.txt_cnf) self.btn.setEnabled(False) else: self.params.objective =\ self.params.columns[self.obj_group.checkedId()] self.lbl_cnf.setText('<br>') self.btn.setEnabled(True) self.params.col_types_changed = True
class exampleQMainWindow (QWidget): def __init__(self): super(exampleQMainWindow, self).__init__() # Create QListWidget self.myQListWidget = QListWidget(self) self.myQListWidget.setStyleSheet(""" QListWidget:item:selected:active { background-color:#A6A4FF;} """) self.setMinimumSize(350, 500) self.config = configparser.ConfigParser() self.config.read('prefs.cfg') self.extention = QLineEdit() self.filename = QLineEdit() self.add_type = QPushButton("add type") self.del_type = QPushButton("del type") self.color_button = color_picker(parent=self) self.pattern_icon = Pattern_button(parent=self) self.radio_button_one = QRadioButton('Classic') self.radio_button_two = QRadioButton('Magellan') self.radio_group = QGroupBox('operation mode') self.radio_group.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.pattern_group = QGroupBox('window pattern and text color') self.pattern_group.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.button_group = QButtonGroup() self.button_group.addButton(self.radio_button_one) self.button_group.addButton(self.radio_button_two) self.button_group.setId(self.radio_button_one, 1) self.button_group.setId(self.radio_button_two, 2) self.mainlayout = QVBoxLayout() self.holdgroups_layout = QHBoxLayout() self.radio_button_layout = QVBoxLayout() self.pattern_label_layout = QHBoxLayout() self.add_filetype_layout = QFormLayout() self.add_del_button_layout = QHBoxLayout() # adding self.holdgroups_layout.addWidget(self.radio_group) self.holdgroups_layout.addWidget(self.pattern_group) self.pattern_label_layout.addWidget(self.pattern_icon) self.pattern_label_layout.addStretch(1) self.pattern_label_layout.addWidget(self.color_button) self.pattern_label_layout.addStretch(1) self.pattern_group.setLayout(self.pattern_label_layout) self.radio_button_layout.addWidget(self.radio_button_one) self.radio_button_layout.addWidget(self.radio_button_two) self.radio_group.setLayout(self.radio_button_layout) self.add_filetype_layout.addRow('extention', self.extention) self.add_filetype_layout.addRow('path to icon', self.filename) self.add_del_button_layout.addWidget(self.add_type) self.add_del_button_layout.addWidget(self.del_type) # layouts settings # self.radio_button_layout.setGeometry(QRect(10, 10, 10, 10)) self.add_filetype_layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) # self.pattern_icon.setPixmap(QPixmap("./images/pattern.png").scaledToWidth(80)) self.mainlayout.setContentsMargins(5, 5, 5, 0) self.mainlayout.setSpacing(7) # reading stored settings for key, value in self.config.items('icons'): myQCustomQWidget = QCustomQWidget() myQCustomQWidget.setTextUp("filetype: " + key.upper()) myQCustomQWidget.setTextDown(value) myQCustomQWidget.setIcon(os.path.dirname(os.path.realpath(__file__)) + value) myQListWidgetItem = QListWidgetItem(self.myQListWidget) myQListWidgetItem.setSizeHint(myQCustomQWidget.sizeHint()) self.myQListWidget.addItem(myQListWidgetItem) self.myQListWidget.setItemWidget(myQListWidgetItem, myQCustomQWidget) # adding elements to layout self.mainlayout.addLayout(self.holdgroups_layout) self.mainlayout.insertSpacing(10, 10) self.mainlayout.addWidget(self.myQListWidget) self.mainlayout.addLayout(self.add_filetype_layout) self.mainlayout.addLayout(self.add_del_button_layout) self.setLayout(self.mainlayout)
class Radiobuttons(QWidget): """ Create grouped radio button widget for language choice """ def __init__(self, label, instruction, button_list, states): super(Radiobuttons, self).__init__() self.states = states self.default = -1 self.id = None self.frame = QFrame(self) self.frame.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.frame.setStyleSheet("border: 1px solid gray; border-radius: 10px;" "background-color: rgb(230, 200, 167);") # self.frame.setStyleSheet("border: 1px solid gray; border-radius: 10px; # background-color: rgba(230, 200, 167);") self.setMinimumSize(300, 300) self.setAutoFillBackground(True) self.title_label = QLabel(label) self.title_label.setFont(QFont("Arial", 18)) self.title_label.setAlignment(Qt.AlignCenter) self.instruct_label = QLabel(instruction) self.instruct_label.setFont(QFont("Arial", 14)) self.instruct_label.setAlignment(Qt.AlignCenter) self.radio_group_box = QGroupBox() self.radio_group_box.setObjectName( "ColoredGroupBox") # Changed here... self.radio_group_box.setStyleSheet("""QGroupBox#ColoredGroupBox{ border: 1px solid gray; border-radius: 10px; background-color: rgb(230, 200, 167); margin-top: 10px; margin-bottom: 10px; margin-left: 20px; margin-right: 20px;}""") self.radio_group_box.setFont(QFont("Helvetica MS", 18)) self.radio_button_group = QButtonGroup() self.setAttribute(Qt.WA_TranslucentBackground) self.radio_button_list = [] for b in button_list: rb = QRadioButton(b) rb.setStyleSheet("""QRadioButton{ font: 14pt Arial; background-color: rgb(230, 200, 167); border: 0px; padding: 4px;} QRadioButton::indicator{ width: 20px; height: 30px;}""") self.radio_button_list.append(rb) self.radio_button_layout = QVBoxLayout() counter = 0 for b in self.radio_button_list: self.radio_button_layout.addWidget(b) self.radio_button_group.addButton(b) self.radio_button_group.setId(b, counter) b.clicked.connect(self.radio_button_clicked) counter += 1 self.radio_group_box.setLayout(self.radio_button_layout) self.main_layout = QVBoxLayout(self.frame) self.main_layout.setSpacing(20) self.main_layout.addWidget(self.title_label) self.main_layout.addWidget(self.radio_group_box) self.main_layout.addStretch(1) self.main_layout.addWidget(self.instruct_label) self.setLayout(self.main_layout) def set_frame(self, on): """ Turn frame around radio burtton widget on and off """ if on: self.frame.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.frame.setStyleSheet( "border: 1px solid gray; border-radius: 10px;" "background-color: rgb(230, 200, 167);") else: self.frame.setStyleSheet( "border: 0px solid gray; border-radius: 10px;" "background-color: rgb(230, 200, 167);") def set_default(self, val): """ Set default button """ self.default = val self.radio_button_list[self.default].setChecked(True) def set_ID(self, player_id): """ Set ID for radiobuutons """ self.id = player_id def resizeEvent(self, event): """ Deal with resize event """ self.frame.resize(self.size()) QWidget.resizeEvent(self, event) def radio_button_clicked(self): """ Store ID of checked button when clicked """ self.states.machine.radio_complete.emit( self.radio_button_group.checkedId(), self.id)
class App(QWidget): def __init__(self): super(App, self).__init__() Form, Window = uic.loadUiType("mainWin.ui") self.window = Window() form = Form() form.setupUi(self.window) self.window.show() self.updated = 1 self.scale = 0.00392 self.classes = None with open(classesPath, 'r') as f: self.classes = [line.strip() for line in f.readlines()] self.COLORS = np.random.uniform(0, 255, size=(len(self.classes), 3)) self.net = cv2.dnn.readNet(weightsPath, configPath) self.ln = self.net.getLayerNames() self.ln = [ self.ln[i[0] - 1] for i in self.net.getUnconnectedOutLayers() ] self.savedImages = [] self.seen = set() self.saveCounter = 0 self.flag = 1 self.segmentationFlag = 0 self.savedPos = 0 self.label = form.loadedImgLbl self.quitBut = form.qbtn.clicked.connect(self.quitApp) self.loadImButton = form.loadIm.clicked.connect(self.loadImageFunction) self.loadVidButton = form.loadVid.clicked.connect( self.loadVideoFunction) self.boundingBoxes = form.boundingBoxes self.boundingBoxes.clicked.connect(self.boundingBoxesFunction) self.segmentationButton = form.segmentationButton self.segmentationButton.clicked.connect(self.segmentationFunction) self.updateBoxes = form.updateBoxes self.updateBoxes.clicked.connect(self.updateBoxesFunction) self.originalImage = form.originalImage self.originalImage.clicked.connect(self.originalImageFunction) self.showLibButton = form.saveToLib self.showLibButton.clicked.connect(self.saveToLibFunction) self.loadSavedButton = form.loadBtn self.loadSavedButton.clicked.connect(self.loadSavedFunction) self.addLabel = form.addLabel self.addLabel.clicked.connect(self.addLabelFunction) self.moveLabel = form.moveLabel self.moveLabel.clicked.connect(self.moveLabelFunction) self.adjustSizeButton = form.adjustSize self.adjustSizeButton.clicked.connect(self.adjustSizeFunction) self.deleteLabel = form.deleteLabel self.deleteLabel.clicked.connect(self.deleteLabelFunction) self.savedBoxes = QButtonGroup() self.savedBoxes.setExclusive(True) self.detTable = form.detailsTable self.video = 0 with open('bounding_boxes.csv', mode='w') as bounding_file: csv.writer(bounding_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) app.exec_() # Used to load the original image selected by the user def originalImageFunction(self): self.emptyTable() self.flag = 1 self.segmentationFlag = 0 self.updateImage() # Used to update the shown image in the GUI def updateImage(self): size = max(self.pixmap.height(), self.pixmap.width()) if (self.flag == 1) and (self.segmentationFlag == 0): if not (self.video): self.image = cv2.imread(self.loadedImage) cv2.imwrite("object-detection.jpg", self.image) self.label.setPixmap(QPixmap('object-detection.jpg')) self.emptyTable() elif (self.flag == 1) and (self.segmentationFlag == 1): self.label.setPixmap(QPixmap('segmented-image.jpg')) self.emptyTable() self.image = self.segmImage elif (self.flag == 0) and (self.segmentationFlag == 0): if not (self.video): self.image = cv2.imread(self.loadedImage) for i in self.im_indices: i = i[0] box = self.im_boxes[i] x = box[0] y = box[1] w = box[2] h = box[3] self.draw_bounding_box(self.image, str(self.classes[self.classes_ids[i]]), self.classes_ids[i], round(x), round(y), round(x + w), round(y + h), size / 1000, 2) cv2.imwrite("object-detection.jpg", self.image) self.label.setPixmap(QPixmap('object-detection.jpg')) self.fillTable() elif (self.flag == 0) and (self.segmentationFlag == 1): imageTmp = self.segmImage if self.updated: for i in self.im_indices: i = i[0] box = self.im_boxes[i] x = box[0] y = box[1] w = box[2] h = box[3] self.draw_bounding_box( imageTmp, str(self.classes[self.classes_ids[i]]), self.classes_ids[i], round(x), round(y), round(x + w), round(y + h), size / 1000, 2) else: self.updateBoxesFunction() cv2.imwrite("object-detection.jpg", imageTmp) self.label.setPixmap(QPixmap('object-detection.jpg')) self.fillTable() # Used to add a new label as a bounding box to the image def addLabelFunction(self): self.addClicked = 1 self.leftClicked = 0 alert = QMessageBox() alert.setWindowTitle("Add a new Box") alert.setStandardButtons(QMessageBox.Ok) alert.setIcon(QMessageBox.Information) alert.setText( 'Use Left Click to set the top left corner and then, right click to set the bottom right corner.' ) alert.exec() self.label.mousePressEvent = self.getPos # Used to get the position that the left/right mouse click was clicked on the image and add the new label def getPos(self, event): if (event.button() == Qt.LeftButton) and ( self.addClicked) and not (self.leftClicked): self.leftClicked = 1 self.x_begin = round(event.pos().x() * self.ratio) self.y_begin = round(event.pos().y() * self.ratio) elif (event.button() == Qt.RightButton) and (self.addClicked) and (self.leftClicked): x_end = round(event.pos().x() * self.ratio) y_end = round(event.pos().y() * self.ratio) self.addClicked = 0 new_label = self.inputDialogLabel() if new_label in self.classes: index = self.classes.index(new_label) self.draw_bounding_box(self.image, str(self.classes[index]), index, round(self.x_begin), round(self.y_begin), round(x_end), round(y_end), 0.8, 2) else: index = -1 self.draw_bounding_box(self.image, str(new_label), index, round(self.x_begin), round(self.y_begin), round(x_end), round(y_end), 0.8, 2) index = self.classes.index(new_label) self.classes_ids.append(index) self.im_boxes.append([ self.x_begin, self.y_begin, x_end - self.x_begin, y_end - self.y_begin ]) if (len(self.im_indices) == 0): self.im_indices = [[0]] else: self.im_indices = np.vstack( (self.im_indices, len(self.im_indices))) self.updateImage() self.fillTable() if not (self.segmFlag): self.image = cv2.imread(self.loadedImage) mask = np.zeros(self.image.shape[:2], np.uint8) bgdModel = np.zeros((1, 65), np.float64) fgdModel = np.zeros((1, 65), np.float64) box = self.im_boxes[self.selectedCheckbox] rect = (int(box[0]), int(box[1]), int(box[2]), int(box[3])) cv2.grabCut(self.image, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT) mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8') self.segmImage = self.segmImage + self.image * mask2[:, :, np. newaxis] for y in range(0, self.image.shape[0]): for x in range(0, self.image.shape[1]): if (self.segmImage[y][x][0] == 0) and (self.segmImage[y][x][1] == 0) and (self.segmImage[y][x][2] == 0): self.segmImage[y][x][0] = 0 self.segmImage[y][x][1] = 0 self.segmImage[y][x][2] = self.gray[y][x] elif (self.segmImage[y][x][0] == 255) and (self.segmImage[y][x][1] == 255) and (self.segmImage[y][x][2] == 255): self.segmImage[y][x][0] = 0 self.segmImage[y][x][1] = 0 self.segmImage[y][x][2] = 255 self.image = self.segmImage cv2.imwrite("segmented-image.jpg", self.segmImage) # Used to warn the user to add a label to the new bounding box def inputDialogLabel(self): text, ok = QInputDialog.getText(self, 'New Label Input Dialog', 'Enter a label of object:') le = QLineEdit() if ok: le.setText(str(text)) return (text) # Used to move an existing bounding box of the image by pressing the left mouse click def moveLabelFunction(self): alert = QMessageBox() alert.setWindowTitle("Move a Box") alert.setStandardButtons(QMessageBox.Ok) if self.selectedCheckbox == -1: alert.setIcon(QMessageBox.Warning) alert.setText( 'You have not selected a box to move. Please select and try again. Do not forget to press "Update" before trying to move !' ) alert.exec() else: alert.setIcon(QMessageBox.Information) alert.setText('Use Left Click to set the top left corner.') alert.exec() self.label.mousePressEvent = self.movePos # Used to move the selected box to a new position in the image def movePos(self, event): if (event.button() == Qt.LeftButton): x_pressed = round(event.pos().x() * self.ratio) y_pressed = round(event.pos().y() * self.ratio) self.im_boxes[self.selectedCheckbox][0] = x_pressed self.im_boxes[self.selectedCheckbox][1] = y_pressed self.fillTable() self.updateBoxesFunction() # Used to adjust the size of an existing bounding box of the image def adjustSizeFunction(self): alert = QMessageBox() alert.setWindowTitle("Adjust the size of a Box") alert.setStandardButtons(QMessageBox.Ok) if self.selectedCheckbox == -1: alert.setIcon(QMessageBox.Warning) alert.setText( 'You have not selected a box to adjust its size. Please select and try again. Do not forget to press "Update" before trying to adjust the size of a box !' ) alert.exec() else: alert.setIcon(QMessageBox.Information) alert.setText( 'Use Left Click to set the top left corner, or right click to set the bottom right corner.' ) alert.exec() self.label.mousePressEvent = self.adjustSize # Adjust the size of a bounding box based on which click was pressed def adjustSize(self, event): if (event.button() == Qt.LeftButton): x_pressed = round(event.pos().x() * self.ratio) y_pressed = round(event.pos().y() * self.ratio) self.im_boxes[self.selectedCheckbox][2] = -( x_pressed - self.im_boxes[self.selectedCheckbox][0] ) + self.im_boxes[self.selectedCheckbox][2] self.im_boxes[self.selectedCheckbox][3] = -( y_pressed - self.im_boxes[self.selectedCheckbox][1] ) + self.im_boxes[self.selectedCheckbox][3] self.im_boxes[self.selectedCheckbox][0] = x_pressed self.im_boxes[self.selectedCheckbox][1] = y_pressed elif (event.button() == Qt.RightButton): x_pressed = round(event.pos().x() * self.ratio) y_pressed = round(event.pos().y() * self.ratio) self.im_boxes[self.selectedCheckbox][ 2] = x_pressed - self.im_boxes[self.selectedCheckbox][0] self.im_boxes[self.selectedCheckbox][ 3] = y_pressed - self.im_boxes[self.selectedCheckbox][1] self.fillTable() self.updateBoxesFunction() # Deletes an existing bounding box from the image def deleteLabelFunction(self): alert = QMessageBox() alert.setIcon(QMessageBox.Warning) alert.setWindowTitle("Delete a Box") if self.selectedCheckbox == -1: alert.setStandardButtons(QMessageBox.Ok) alert.setText( 'You have not selected a box to delete. Please select and try again. Do not forget to press "Update" before trying to delete !' ) alert.exec() else: alert.setStandardButtons(QMessageBox.Yes | QMessageBox.No) alert.setText('Are you sure you want to delete this box ?') returnValue = alert.exec() if returnValue == QMessageBox.Yes: del self.classes_ids[self.selectedCheckbox] tmp = np.array([[0]]) self.im_indices = np.delete(self.im_indices, self.selectedCheckbox, 0) if not (self.segmFlag): self.image = cv2.imread(self.loadedImage) mask = np.zeros(self.image.shape[:2], np.uint8) bgdModel = np.zeros((1, 65), np.float64) fgdModel = np.zeros((1, 65), np.float64) box = self.im_boxes[self.selectedCheckbox] rect = (int(box[0]), int(box[1]), int(box[2]), int(box[3])) cv2.grabCut(self.image, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT) mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8') self.segmImage = self.segmImage - self.image * mask2[:, :, np. newaxis] for y in range(0, self.image.shape[0]): for x in range(0, self.image.shape[1]): if (self.segmImage[y][x][0] == 0) and ( self.segmImage[y][x][1] == 0) and (self.segmImage[y][x][2] == 0): self.segmImage[y][x][0] = 0 self.segmImage[y][x][1] = 0 self.segmImage[y][x][2] = self.gray[y][x] elif (self.segmImage[y][x][0] == 255) and ( self.segmImage[y][x][1] == 255) and (self.segmImage[y][x][2] == 255): self.segmImage[y][x][0] = 0 self.segmImage[y][x][1] = 0 self.segmImage[y][x][2] = 255 self.image = self.segmImage cv2.imwrite("segmented-image.jpg", self.segmImage) if len(self.im_indices) == 0: tmp = np.array([]) for i in range(1, len(self.im_indices)): tmp = np.vstack((tmp, i)) self.updated = 1 self.im_indices = tmp del self.im_boxes[self.selectedCheckbox][:] del self.im_boxes[self.selectedCheckbox] self.updateImage() # Sets the buttons that the user can click on when he selects the bounding boxes option def boundingBoxesFunction(self): self.selectedCheckbox = -1 if self.flag: self.flag = 0 self.updateBoxes.setEnabled(True) self.addLabel.setEnabled(True) self.moveLabel.setEnabled(True) self.adjustSizeButton.setEnabled(True) self.deleteLabel.setEnabled(True) elif not (self.flag): self.flag = 1 self.updateBoxes.setEnabled(False) self.addLabel.setEnabled(False) self.moveLabel.setEnabled(False) self.adjustSizeButton.setEnabled(False) self.deleteLabel.setEnabled(False) self.updateImage() # Sets the thickness of each bounding box based on his selection def updateBoxesFunction(self): if self.segmentationFlag: self.image = self.segmImage else: if not (self.video): self.image = cv2.imread(self.loadedImage) size = max(self.pixmap.height(), self.pixmap.width()) for i in range(1, self.rows): box = self.im_boxes[i - 1] label = (self.detTable.item(i, 0).text()) x = int(box[0]) y = int(box[1]) w = int(box[2]) h = int(box[3]) if label in self.classes: index = self.classes.index(label) if self.detTable.cellWidget(i, 1).isChecked(): self.selectedCheckbox = i - 1 thickness = size / 571.4286 rect_size = 4 self.draw_bounding_box(self.image, label, index, x, y, (x + w), (y + h), thickness, rect_size) else: rect_size = 2 thickness = size / 1000 self.draw_bounding_box(self.image, label, index, x, y, (x + w), (y + h), thickness, rect_size) elif label not in self.classes: index = -1 if self.detTable.cellWidget(i, 1).isChecked(): self.selectedCheckbox = i - 1 thickness = size / 571.4286 rect_size = 4 self.draw_bounding_box(self.image, label, index, x, y, (x + w), (y + h), thickness, rect_size) index = self.classes.index(label) else: rect_size = 2 thickness = size / 1000 self.draw_bounding_box(self.image, label, index, x, y, (x + w), (y + h), thickness, rect_size) index = self.classes.index(label) self.classes_ids[i - 1] = index cv2.imwrite("object-detection.jpg", self.image) self.updated = 0 self.label.setPixmap(QPixmap('object-detection.jpg')) # Quits the application def quitApp(self): QApplication.quit() # Saves the image and its bounding boxes into a temporary library. Saved in COCO format def saveToLibFunction(self): if self.loadedImage in self.seen: print("Already in library") else: self.loadSavedButton.setEnabled(True) self.seen.add(self.loadedImage) self.savedImages.append({ 'id': self.saveCounter, 'loaded_path': self.loadedImage, 'indices': self.im_indices, 'boxes': self.im_boxes, 'classes_ids': self.classes_ids }) with open('bounding_boxes.csv', mode='a') as bounding_file: bounding_writer = csv.writer(bounding_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) bounding_writer.writerow([ self.saveCounter, self.loadedImage, self.im_indices, self.im_boxes, self.classes_ids ]) self.image = cv2.imread(self.loadedImage) cv2.imwrite("object-detection.jpg", self.image) labelName = "label" + str(self.saveCounter) labelName = QLabel(self.window) labelName.setScaledContents(True) labelName.setGeometry(790 + 110 * (self.savedPos % 2), 50 + 100 * int(self.savedPos / 2), 90, 70) labelName.setPixmap(QPixmap('object-detection.jpg')) labelName.show() checkName = "chkBoxItem" + str(self.saveCounter) checkName = QCheckBox(self.window) self.savedBoxes.addButton(checkName) checkName.setCheckState(Qt.Unchecked) checkName.move(830 + 110 * (self.savedPos % 2), 120 + 100 * int(self.savedPos / 2)) checkName.show() self.savedBoxes.setId(checkName, self.saveCounter) self.saveCounter += 1 self.savedPos += 1 if (self.savedPos == 12): self.savedPos = 0 # Loads the image selected by the user and its bounding boxes and shows it in the GUI def loadSavedFunction(self): checkedBox = self.savedBoxes.checkedId() if checkedBox != (-1): self.image = cv2.imread( self.savedImages[checkedBox]['loaded_path']) self.pixmap = QPixmap(self.savedImages[checkedBox]['loaded_path']) self.label.setScaledContents(True) self.label.setPixmap(self.pixmap) if (self.pixmap.width() > 660) or (self.pixmap.height() > 660): self.ratio = max(self.pixmap.width() / 660, self.pixmap.height() / 660) + 0.71 self.label.resize(self.pixmap.width() / self.ratio, self.pixmap.height() / self.ratio) pixmapWidth = self.pixmap.width() / self.ratio pixmapHeight = self.pixmap.height() / self.ratio else: self.label.resize(self.pixmap.width(), self.pixmap.height()) pixmapWidth = self.pixmap.width() pixmapHeight = self.pixmap.height() self.label.move(660 / 2 - pixmapWidth / 2, 660 / 2 - pixmapHeight / 2) cv2.imwrite("object-detection.jpg", self.image) self.loadedImage = self.savedImages[checkedBox]['loaded_path'] self.classes_ids = self.savedImages[checkedBox]['classes_ids'] self.im_indices = self.savedImages[checkedBox]['indices'] self.im_boxes = self.savedImages[checkedBox]['boxes'] self.label.setPixmap(QPixmap('object-detection.jpg')) self.segmImage = np.zeros((self.image.shape)) self.gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY) self.flag = 1 self.segmentationFlag = 0 self.segmFlag = 1 self.updateImage() # Loads a video selected by the user def loadVideoFunction(self): self.label.setText('Loading....') desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop') self.loadedVideo = QFileDialog.getOpenFileName(None, 'Open file', desktop)[0] self.pixmap = QPixmap(self.loadedVideo) self.label.setScaledContents(True) self.label.setPixmap(self.pixmap) self.boundingBoxes.setEnabled(True) self.originalImage.setEnabled(True) self.pauseButton = QPushButton(self.window) self.pauseButton.clicked.connect(self.pauseFunction) self.pauseButton.setGeometry(93, 565, 90, 30) self.pauseButton.setText("Pause") self.pauseButton.show() self.playButton = QPushButton(self.window) self.playButton.clicked.connect(self.playFunction) self.playButton.setGeometry(183, 565, 90, 30) self.playButton.setText("Play") self.playButton.show() self.pauseFlag = 0 pixmapWidth = 660 * 0.71 pixmapHeight = 660 * 0.71 self.label.resize(pixmapWidth, pixmapHeight) self.label.move(660 / 2 - pixmapWidth / 2, 660 / 2 - pixmapHeight / 2) self.video = 1 self.flag = 1 self.segmentationFlag = 0 cap = cv2.VideoCapture(self.loadedVideo) while (cap.isOpened()): if (self.pauseFlag == 0): ret, frame = cap.read() if ret: self.image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) h, w, ch = self.image.shape self.blob = cv2.dnn.blobFromImage(self.image, self.scale, (416, 416), (0, 0, 0), True, crop=False) self.net.setInput(self.blob) self.yoloPredImage() cv2.imwrite("object-detection.jpg", self.image) self.updateImage() self.label.setPixmap(QPixmap('object-detection.jpg')) if cv2.waitKey(25) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() self.video = 0 def pauseFunction(self): self.pauseFlag = 1 self.updateBoxes.setEnabled(True) self.addLabel.setEnabled(True) self.moveLabel.setEnabled(True) self.adjustSizeButton.setEnabled(True) self.deleteLabel.setEnabled(True) def playFunction(self): self.pauseFlag = 0 self.updateBoxes.setEnabled(False) self.addLabel.setEnabled(False) self.moveLabel.setEnabled(False) self.adjustSizeButton.setEnabled(False) self.deleteLabel.setEnabled(False) # Loads an image based on the user's selection def loadImageFunction(self): self.label.setText('Loading....') desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop') self.loadedImage = QFileDialog.getOpenFileName(None, 'Open file', desktop)[0] self.pixmap = QPixmap(self.loadedImage) self.label.setScaledContents(True) self.label.setPixmap(self.pixmap) self.segmentationFlag = 0 self.flag = 1 self.image = cv2.imread(self.loadedImage) self.segmImage = np.zeros((self.image.shape)) self.gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY) if (self.pixmap.width() > 660) or (self.pixmap.height() > 660): self.ratio = max(self.pixmap.width() / 660, self.pixmap.height() / 660) + 0.71 self.label.resize(self.pixmap.width() / self.ratio, self.pixmap.height() / self.ratio) pixmapWidth = self.pixmap.width() / self.ratio pixmapHeight = self.pixmap.height() / self.ratio else: self.ratio = 1 self.label.resize(self.pixmap.width(), self.pixmap.height()) pixmapWidth = self.pixmap.width() pixmapHeight = self.pixmap.height() self.label.move(660 / 2 - pixmapWidth / 2, 660 / 2 - pixmapHeight / 2) self.blob = cv2.dnn.blobFromImage(self.image, self.scale, (416, 416), (0, 0, 0), True, crop=False) self.net.setInput(self.blob) self.yoloPredImage() self.showLibButton.setEnabled(True) self.boundingBoxes.setEnabled(True) self.segmentationButton.setEnabled(True) self.originalImage.setEnabled(True) self.segmFlag = 1 cv2.imwrite("object-detection.jpg", self.image) self.label.setPixmap(QPixmap('object-detection.jpg')) self.emptyTable() # Uses YOLO pre-trained CNN to identify objects into the image def yoloPredImage(self): outs = self.net.forward(self.get_output_layers()) Width = self.image.shape[1] Height = self.image.shape[0] class_ids = [] confidences = [] boxes = [] conf_threshold = 0.5 nms_threshold = 0.4 for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: center_x = int(detection[0] * Width) center_y = int(detection[1] * Height) w = int(detection[2] * Width) h = int(detection[3] * Height) x = center_x - w / 2 y = center_y - h / 2 class_ids.append(class_id) confidences.append(float(confidence)) boxes.append([x, y, w, h]) indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold) self.classes_ids = class_ids self.im_indices = indices self.im_boxes = boxes # Fills a table with the objects identified by YOLO and gives the ability to the user to select one of those def fillTable(self): headers = ["Label", "Check"] self.col = len(headers) self.rows = len(self.classes_ids) + 1 self.checkBoxes = QButtonGroup(self.detTable) self.checkBoxes.setExclusive(True) self.detTable.setRowCount(self.rows) self.detTable.setColumnCount(self.col) for i in range(0, self.col): self.detTable.setItem(0, i, QTableWidgetItem(headers[i])) for i in range(1, self.rows): self.detTable.setItem( i, 0, QTableWidgetItem(self.classes[self.classes_ids[i - 1]])) name = "chkBoxItem" + str(i) name = QCheckBox() self.checkBoxes.addButton(name) name.setCheckState(Qt.Unchecked) self.detTable.setCellWidget(i, 1, name) for j in range(1, self.col - 1): self.detTable.setItem( i, j, QTableWidgetItem(str(round(self.im_boxes[i - 1][j - 1])))) self.detTable.resizeColumnsToContents() # Empties the table filled with the objects identified by YOLO algorithm def emptyTable(self): self.col = 0 self.rows = 0 self.detTable.setRowCount(self.rows) self.detTable.setColumnCount(self.col) def get_output_layers(self): layer_names = self.net.getLayerNames() self.output_layers = [ layer_names[i[0] - 1] for i in self.net.getUnconnectedOutLayers() ] return self.output_layers # Draws a bounding box for each identified object of the image def draw_bounding_box(self, img, label, class_id, x, y, x_plus_w, y_plus_h, thickness, rect_size): if class_id == -1: color = np.random.uniform(0, 255, 3) choice = self.new_label_addition(label, color) if choice == 1: cv2.rectangle(img, (x, y), (x_plus_w, y_plus_h), color, rect_size) cv2.putText(img, label, (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, thickness, color, 2) else: cv2.rectangle(img, (x, y), (x_plus_w, y_plus_h), color, rect_size) else: color = self.COLORS[class_id] cv2.rectangle(img, (x, y), (x_plus_w, y_plus_h), color, rect_size) cv2.putText(img, label, (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, thickness, color, 2) # Warns the user that the label that he is about to add is not included in the dataset and asks him if he wants to add it def new_label_addition(self, label, color): alert = QMessageBox() alert.setIcon(QMessageBox.Information) alert.setWindowTitle("New label") alert.setStandardButtons(QMessageBox.Yes | QMessageBox.No) alert.setText( 'This label is not in the existing dataset, would you like to add it ?' ) returnValue = alert.exec() choice = 0 if returnValue == QMessageBox.Yes: self.classes.append(label) self.COLORS = np.vstack([self.COLORS, color]) choice = 1 return (choice) # Centers the GUI in the center of the screen def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) # Uses te GraphCut method to segment the image def segmentationFunction(self): self.image = cv2.imread(self.loadedImage) mask = np.zeros(self.image.shape[:2], np.uint8) bgdModel = np.zeros((1, 65), np.float64) fgdModel = np.zeros((1, 65), np.float64) if self.segmFlag: self.segmFlag = 0 if (len(self.im_indices) != 0): for i in self.im_indices: i = i[0] box = self.im_boxes[i] rect = (int(box[0]), int(box[1]), int(box[2]), int(box[3])) cv2.grabCut(self.image, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT) mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8') self.segmImage = self.segmImage + self.image * mask2[:, :, np. newaxis] for y in range(0, self.image.shape[0]): for x in range(0, self.image.shape[1]): if (self.segmImage[y][x][0] == self.segmImage[y][x][1] ) and (self.segmImage[y][x][2] == self.segmImage[y][x][1]): self.segmImage[y][x][0] = 0 self.segmImage[y][x][1] = 0 self.segmImage[y][x][2] = self.gray[y][x] cv2.imwrite("segmented-image.jpg", self.segmImage) if not (self.segmentationFlag): self.segmentationFlag = 1 else: self.segmentationFlag = 0 self.updateImage()
def request_safe_t_init_settings(self, wizard, method, device): vbox = QVBoxLayout() next_enabled = True label = QLabel(_("Enter a label to name your device:")) name = QLineEdit() hl = QHBoxLayout() hl.addWidget(label) hl.addWidget(name) hl.addStretch(1) vbox.addLayout(hl) def clean_text(widget): text = widget.toPlainText().strip() return ' '.join(text.split()) if method in [TIM_NEW, TIM_RECOVER]: gb = QGroupBox() hbox1 = QHBoxLayout() gb.setLayout(hbox1) vbox.addWidget(gb) gb.setTitle(_("Select your seed length:")) bg = QButtonGroup() for i, count in enumerate([12, 18, 24]): rb = QRadioButton(gb) rb.setText(_("{:d} words").format(count)) bg.addButton(rb) bg.setId(rb, i) hbox1.addWidget(rb) rb.setChecked(True) cb_pin = QCheckBox(_('Enable PIN protection')) cb_pin.setChecked(True) else: text = QTextEdit() text.setMaximumHeight(60) if method == TIM_MNEMONIC: msg = _("Enter your BIP39 mnemonic:") else: msg = _("Enter the master private key beginning with xprv:") def set_enabled(): from vialectrum.bip32 import is_xprv wizard.next_button.setEnabled(is_xprv(clean_text(text))) text.textChanged.connect(set_enabled) next_enabled = False vbox.addWidget(QLabel(msg)) vbox.addWidget(text) pin = QLineEdit() pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,9}'))) pin.setMaximumWidth(100) hbox_pin = QHBoxLayout() hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):"))) hbox_pin.addWidget(pin) hbox_pin.addStretch(1) if method in [TIM_NEW, TIM_RECOVER]: vbox.addWidget(WWLabel(RECOMMEND_PIN)) vbox.addWidget(cb_pin) else: vbox.addLayout(hbox_pin) passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT) passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN) passphrase_warning.setStyleSheet("color: red") cb_phrase = QCheckBox(_('Enable passphrases')) cb_phrase.setChecked(False) vbox.addWidget(passphrase_msg) vbox.addWidget(passphrase_warning) vbox.addWidget(cb_phrase) wizard.exec_layout(vbox, next_enabled=next_enabled) if method in [TIM_NEW, TIM_RECOVER]: item = bg.checkedId() pin = cb_pin.isChecked() else: item = ' '.join(str(clean_text(text)).split()) pin = str(pin.text()) return (item, name.text(), pin, cb_phrase.isChecked())
class SegmentationMenu(QFrame): def __init__(self, parent): super(SegmentationMenu, self).__init__(parent) # QWidget Label at the top label = QLabel('View Toolbox') label.setStyleSheet(Settings.menu_font) # Menus for segmentation activation and representation in slice view slice_btn = PushButton( self, "Slice View", ["Show Slices", "Boundary overlay", "Mask Overlay"]) segm_btn = PushButton(self, "Active Masks", ["Ground Truth", "DNN-Segmentation"]) rend_btn = PushButton( self, "3D View", ["Volumetric", "Surface", "Coordinates", "All Organs", "Stereo"]) self.combobox = QtWidgets.QComboBox() self.combobox.setObjectName("Label Choosing") pix_map = QPixmap(12, 12) pix_map.fill(QColor(0, 0, 0)) self.combobox.addItem(QIcon(pix_map), 'No active label') for organ in Settings.organs: pix_map = QPixmap(12, 12) pix_map.fill( QColor(*[255 * c for c in Settings.labels[organ]['rgb']])) self.combobox.addItem(QIcon(pix_map), organ) self.combobox.currentIndexChanged.connect(self.label_selectionchange) titles = ['M', 'Z', 'C', 'P', 'D'] presstype = QWidget() presstype.setObjectName("Key Press Button") l = QtWidgets.QHBoxLayout(presstype) l.setContentsMargins(0, 0, 0, 0) buttons = [] path = Settings.view_icons['path'] for tit, button_icon in enumerate(Settings.view_icons['menu_buttons']): icon = QIcon( path + Settings.view_icons['menu_buttons'][button_icon]['png']) button = QPushButton() button.setIcon(icon) button.setObjectName(titles[tit]) buttons.append(button) self.button_group = QButtonGroup(l) self.button_group.setExclusive(True) for i, button in enumerate(buttons): l.addWidget(button) if i < len(buttons) - 1: self.button_group.addButton(button) self.button_group.setId(button, i + 1) button.setCheckable(True) else: button.clicked.connect(self.histogram_button_signal) buttons[0].setChecked(True) self.button_group.buttonToggled.connect(self.on_button_signal) # Set layout self.layout = QtWidgets.QVBoxLayout() self.setLayout(self.layout) self.layout.addWidget(label) self.layout.addWidget(presstype) self.layout.addWidget(segm_btn) self.layout.addWidget(slice_btn) self.layout.addWidget(rend_btn) self.layout.addWidget(self.combobox) # Set shape of this QWidget self.setFrameShape(QtWidgets.QFrame.StyledPanel) self.setFrameShadow(QtWidgets.QFrame.Raised) self.setObjectName("Segmentation Menu Window") # Turn off the segmentation functionality segm_btn.slice_menu.findChild(QAction, "DNN-Segmentation").setEnabled(False) segm_btn.slice_menu.findChild(QAction, "Ground Truth").setChecked(True) segm_btn.slice_menu.findChild(QAction, "Ground Truth").setEnabled(False) def on_button_signal(self): button = self.button_group.button(self.button_group.checkedId()) visualization_window = self.parentWidget().get_visualization_widget() if button.objectName() == 'M': visualization_window.change_slice_event_type(0) elif button.objectName() == 'Z': visualization_window.change_slice_event_type(1) elif button.objectName() == 'C': visualization_window.change_slice_event_type(2) elif button.objectName() == 'P': visualization_window.change_slice_event_type(3) def histogram_button_signal(self): visualization_window = self.parentWidget().get_visualization_widget() values, counts = visualization_window.current_data.get_histogram() op_pts = visualization_window.render_list[ -1].vis_object.get_opacity_pts() cmap_name = visualization_window.render_list[-1].vis_object.get_cmap() parent = self.parentWidget().parentWidget() hist = ApplicationWindow(parent, op_pts, values, counts, cmap_name) #hist.setFixedSize(hist.size()) hist.show() # Set the volume slider range volume_range = visualization_window.get_volume_lookup() #hist.set_volume_sliders(volume_range) # Set the Slice sliders range slice_range, slice_value_range = visualization_window.get_slices_lookup( ) hist.set_slice_sliders(slice_range, slice_value_range) def label_selectionchange(self): view_3D = self.findChild(QPushButton, "3D View") all_organs = view_3D.slice_menu.findChild(QAction, "All Organs") if not all_organs.isChecked(): organ = self.combobox.currentText() visualization_window = self.parentWidget( ).get_visualization_widget() visualization_window.handle_surface_rendition(False, organ)