class UriChangerDialog(QDialog): def __init__(self, **kwargs): super().__init__(**kwargs) self.resize(600, 300) self.setLayout(QVBoxLayout()) # FILE SELECT self.sessionLayout = QHBoxLayout() self.layout().addLayout(self.sessionLayout) self.sessionFileEdit = QLineEdit(self) self.sessionFileEdit.editingFinished.connect(self.session_init) self.sessionLayout.addWidget(self.sessionFileEdit) self.sessionFileSelect = QPushButton(self) self.sessionFileSelect.clicked.connect(self.session_select) self.sessionLayout.addWidget(self.sessionFileSelect) self.sessionReload = QPushButton(self) self.sessionReload.setIcon(QIcon.fromTheme('view-refresh')) self.sessionReload.clicked.connect(self.session_init) self.sessionLayout.addWidget(self.sessionReload) # REPLACE self.replaceLayout = QGridLayout() self.layout().addLayout(self.replaceLayout) self.currenLabel = QLabel('Current') self.currenLabel.setAlignment(Qt.AlignCenter) self.replaceLayout.addWidget(self.currenLabel, 0, 0) self.replaceLabel = QLabel('Replace') self.replaceLabel.setAlignment(Qt.AlignCenter) self.replaceLayout.addWidget(self.replaceLabel, 0, 1) self.prefixList = QListWidget(self) self.prefixList.currentTextChanged.connect(self.prefix_changed) self.replaceLayout.addWidget(self.prefixList, 1, 0, 2, 1) self.newPrefixLayout = QVBoxLayout() self.replaceLayout.addLayout(self.newPrefixLayout, 1, 1) self.prefixEdit = QLineEdit(self) self.newPrefixLayout.addWidget(self.prefixEdit) self.replaceLayout.setAlignment(self.prefixEdit, Qt.AlignTop) self.replaceApply = QPushButton(self) self.replaceApply.clicked.connect(self.session_replace) self.newPrefixLayout.addWidget(self.replaceApply) self.newPrefixLayout.setAlignment(self.replaceApply, Qt.AlignRight) self.buttons = QDialogButtonBox(self) self.buttons.setStandardButtons(QDialogButtonBox.Cancel) self.buttons.rejected.connect(self.reject) self.layout().addWidget(self.buttons) self.saveButton = self.buttons.addButton(QDialogButtonBox.Save) self.saveButton.clicked.connect(self.session_save) self.retranslateUi() self.session = None def retranslateUi(self): self.sessionFileSelect.setText('Session file') self.sessionReload.setToolTip('Reload') self.replaceApply.setText('Replace') def prefix_changed(self, prefix): if self.prefixEdit.text() == '': self.prefixEdit.setText(prefix) else: # Search if the prefixEdit text is one of the listed prefixes lower = 0 upper = self.prefixList.count() - 1 search = self.prefixEdit.text() while lower <= upper: middle = (lower + upper) // 2 item = self.prefixList.item(middle).text() if item < search: lower = middle + 1 elif item > search: upper = middle - 1 else: self.prefixEdit.setText(prefix) break def session_select(self): file, _ = QFileDialog.getOpenFileName(self, filter='*.lsp', directory=os.getenv('HOME')) if file != '': self.sessionFileEdit.setText(file) self.session_init() def session_analyze(self): self.prefixList.clear() self.prefixList.addItems(self.session.analyze()) self.prefixList.sortItems() def session_init(self): file = self.sessionFileEdit.text() if os.path.exists(file): self.session = Session(file) self.session_analyze() elif file.strip() != '': QMessageBox.critical(self, 'Error', 'Session file "' + file + '" not found') def session_replace(self): self.session.replace(self.prefixList.currentItem().text(), self.prefixEdit.text()) self.session_analyze() def session_save(self): file, ok = QFileDialog.getSaveFileName(self, filter='*.lsp', directory=os.getenv('HOME')) if ok: self.session.save(file) self.accept()
class PageProjectType(QWizardPage): def __init__(self, wizard): super(PageProjectType, self).__init__() self.setTitle(_translate("PageProjectType", "Project Type")) self.setSubTitle(_translate("PageProjectType", "Choose the Project Type")) self._wizard = wizard vbox = QVBoxLayout(self) self.listWidget = QListWidget() vbox.addWidget(self.listWidget) types = settings.get_all_project_types() types.sort() index = types.index('Python') types.insert(0, types.pop(index)) self.listWidget.addItems(types) self.listWidget.setCurrentRow(0) self.listWidget.itemClicked['QListWidgetItem*'].connect(self.load_pages) def validatePage(self): self._wizard.option = self.listWidget.currentItem().text() return True def load_pages(self): self.wizard().add_project_pages(self.listWidget.currentItem().text())
class LayerActionsDialog(QDialog): def __init__(self, currentGlyph, parent=None): super().__init__(parent) self.setWindowModality(Qt.WindowModal) self.setWindowTitle(self.tr("Layer actions…")) self._workableLayers = [] for layer in currentGlyph.layerSet: if layer != currentGlyph.layer: self._workableLayers.append(layer) layout = QGridLayout(self) copyBox = QRadioButton(self.tr("Copy"), self) moveBox = QRadioButton(self.tr("Move"), self) swapBox = QRadioButton(self.tr("Swap"), self) self.otherCheckBoxes = (moveBox, swapBox) copyBox.setChecked(True) self.layersList = QListWidget(self) self.layersList.addItems( layer.name for layer in self._workableLayers) if self.layersList.count(): self.layersList.setCurrentRow(0) self.layersList.itemDoubleClicked.connect(self.accept) buttonBox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) l = 0 layout.addWidget(copyBox, l, 0, 1, 2) layout.addWidget(moveBox, l, 2, 1, 2) layout.addWidget(swapBox, l, 4, 1, 2) l += 1 layout.addWidget(self.layersList, l, 0, 1, 6) l += 1 layout.addWidget(buttonBox, l, 0, 1, 6) self.setLayout(layout) @classmethod def getLayerAndAction(cls, parent, currentGlyph): dialog = cls(currentGlyph, parent) result = dialog.exec_() currentItem = dialog.layersList.currentItem() newLayer = None if currentItem is not None: newLayerName = currentItem.text() for layer in dialog._workableLayers: if layer.name == newLayerName: newLayer = layer action = "Copy" for checkBox in dialog.otherCheckBoxes: if checkBox.isChecked(): action = checkBox.text() return (newLayer, action, result)
class NapalmInterfaces(QWidget): napalm_actions = ( 'Interfaces', 'Interface IP', 'Interfaces counters', ) @update_paths def __init__(self, node, controller): super().__init__() self.node = node action_label = QLabel('Action') object_label = QLabel('Object') self.object_list = QListWidget() self.object_list.setSortingEnabled(True) self.object_list.itemSelectionChanged.connect(self.text_update) self.action_list = QListWidget() self.action_list.setSortingEnabled(True) self.action_list.itemSelectionChanged.connect(self.text_update) self.action_list.addItems(self.napalm_actions) self.properties_edit = QConsoleEdit() self.properties_edit.setMinimumSize(300, 300) layout = QGridLayout() layout.addWidget(object_label, 0, 0) layout.addWidget(self.object_list, 1, 0) layout.addWidget(action_label, 0, 1) layout.addWidget(self.action_list, 1, 1) layout.addWidget(self.properties_edit, 2, 0, 1, 2) self.setLayout(layout) def update(self): self.object_list.clear() if 'Interfaces' in self.node.napalm_data: self.object_list.addItems(self.node.napalm_data['Interfaces']) def text_update(self): action = self.action_list.currentItem() object = self.object_list.currentItem() if action and object: self.properties_edit.clear() # we display a dictionnary with the following format: # property1: value1 # property2: value2 action, object = action.text(), object.text() value = str_dict(self.node.napalm_data[action][object]) self.properties_edit.insertPlainText(value)
def left_widget(self): listview = QListWidget(self) listview.addItems([i for i in profiledb.list_all()]) listview.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) btn = QPushButton('left widget', self) btn.setToolTip('Button of the <b>left widget</b>.') btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) layout = QVBoxLayout(self) layout.addWidget(listview) layout.addWidget(btn) layout.addStretch(1) widg = QWidget(self) widg.setLayout(layout) widg.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) return widg
def widgetFeatureList(self): """Create the features pair list widget. """ hbox = QHBoxLayout() selectedFeatureList = QListWidget(self) selectedFeatureList.addItems(self.createFeaturesList(self.selectedFeatures)) removeButton = QPushButton(self.tr('>>')) removeButton.clicked.connect(self.removeFeature) addButton = QPushButton(self.tr('<<')) addButton.clicked.connect(self.addFeature) availableFeatureList = QListWidget(self) availableFeatureList.addItems(self.createFeaturesList(self.availableFeatures)) vbox = QVBoxLayout() vbox.addStretch(1) vbox.addWidget(addButton) vbox.addWidget(removeButton) vbox.addStretch(1) vboxSelected = QVBoxLayout() selectedLabel = QLabel(self.tr('Selected')) selectedLabel.setAlignment(QtCore.Qt.AlignCenter) vboxSelected.addWidget(selectedLabel) vboxSelected.addWidget(selectedFeatureList) vboxAvailable = QVBoxLayout() availableLabel = QLabel(self.tr('Available')) availableLabel.setAlignment(QtCore.Qt.AlignCenter) vboxAvailable.addWidget(availableLabel) vboxAvailable.addWidget(availableFeatureList) hbox.addLayout(vboxSelected) hbox.addLayout(vbox) hbox.addLayout(vboxAvailable) self.selectedFeatureList = selectedFeatureList self.availableFeatureList = availableFeatureList return hbox
class Web(QMainWindow, Ui_ShowWeb): signal_change_stackedWidget = pyqtSignal() '''生成批量浏览网页的界面 ''' def __init__(self, parent=None): super(Web, self).__init__(parent) self.setupUi(self) self.tabWidget.removeTab(1) self.tabWidget.removeTab(0) if not os.path.exists('./asserts'): os.mkdir('./asserts') back_to_first_page_image.save('asserts/首页.png') delete_history_image.save('asserts/删除历史记录.png') self.action_back.setIcon(QIcon('asserts/首页.png')) self.action_delete_history.setIcon(QIcon('asserts/删除历史记录.png')) self.path = './db/multiWeb_Database.db' self.lineEdit_url_list = [] # 每一个tab的网址框 self.browser_list = [] # 每一个tab的webEngineView self.listWidget_list = [] # 每一个tab的目录listWidget self.listWidget_history = QListWidget() self.webAddress_LIST = [] # 保存每次主程序发送来的网址数据 self.webAddress_history_list = [] self.tabWidget.tabCloseRequested.connect(self.tab_close) self.listWidget_history.currentRowChanged.connect( self.change_to_history) self.action_back.triggered.connect(self.action_back_triggerd) self.action_delete_history.triggered.connect( self.action_delete_history_triggerd) def action_back_triggerd(self): self.signal_change_stackedWidget.emit() def action_delete_history_triggerd(self): sign = QMessageBox.information(self, '删除历史记录', '是否删除所有历史记录\n删除后无法找回', QMessageBox.Ok) if sign: db = QSqlDatabase.addDatabase('QSQLITE') db.setDatabaseName(self.path) if db.open(): query = QSqlQuery(db) query.exec('drop table if exists history') query.exec( 'create table history(id int primary key, name vhar, url vhar)' ) # for i in range(len(self.webAddress_history_list)): # self.listWidget_history.takeItem(0) self.listWidget_history.clear() self.webAddress_history_list.clear() db.close() def url_changeed(self): index = self.tabWidget.currentIndex() i = self.listWidget_list[index].currentRow() if i == -1: i = 0 url = self.lineEdit_url_list[index].text() self.webAddress_LIST[index][i] = url browser = self.browser_list[index] browser.setUrl(QUrl(url)) def lineEdit_enterd(self): self.url_changeed() def setTabText_and_to_history(self, i, browser): title = browser.page().title() url = browser.url().toString() self.tabWidget.setTabText(i, title[0:30]) if url.strip() != '' and title.strip() != '': self.listWidget_history.addItem(title[0:50]) self.webAddress_history_list.append(url) self.write_history_to_database(title[0:50], url) def write_history_to_database(self, name, url): db = QSqlDatabase.addDatabase('QSQLITE') db.setDatabaseName(self.path) if db.open(): query = QSqlQuery(db) query.exec('insert into history values({}, "{}", "{}")'.format( len(self.webAddress_history_list), str(name), str(url))) db.close() def load_history_from_database(self): name_list = [] url_list = [] db = QSqlDatabase.addDatabase('QSQLITE') db.setDatabaseName(self.path) if db.open(): query = QSqlQuery(db) query.exec('select name, url from history') while query.next(): name_list.append(str(query.value(0))) url_list.append(str(query.value(1))) db.close() return name_list, url_list def change_to_history(self, i): index = self.tabWidget.currentIndex() url = self.webAddress_history_list[i] browser = self.browser_list[index] browser.setUrl(QUrl(url)) def pushButton_copy_clicked(self): index = self.tabWidget.currentIndex() textEdit = self.lineEdit_url_list[index] clipboard = QApplication.clipboard() clipboard.setText(textEdit.text()) def tab_close(self, i): self.tabWidget.removeTab(i) self.lineEdit_url_list.remove(self.lineEdit_url_list[i]) self.browser_list.remove(self.browser_list[i]) self.webAddress_LIST.remove(self.webAddress_LIST[i]) self.listWidget_list.remove(self.listWidget_list[i]) if self.tabWidget.count() < 1: self.signal_change_stackedWidget.emit() def add_new_tab(self, webAddress_name_list, text): self.setVisible(True) widget = QWidget() layout = QVBoxLayout() layout_h = QHBoxLayout() splitter = QSplitter() splitter.setOrientation(Qt.Horizontal) listWidget = QListWidget() listWidget.setCurrentRow(0) browser = QWebEngineView() lineEdit_url = LineEdit() pushButton_copy = QPushButton('复制网址') splitter.addWidget(listWidget) splitter.addWidget(browser) splitter.addWidget(self.listWidget_history) splitter.setStretchFactor(0, 2) splitter.setStretchFactor(1, 8) splitter.setStretchFactor(2, 1) layout_h.addWidget(lineEdit_url) layout_h.addWidget(pushButton_copy) layout.addLayout(layout_h) layout.addWidget(splitter) widget.setLayout(layout) self.lineEdit_url_list.append(lineEdit_url) self.browser_list.append(browser) self.listWidget_list.append(listWidget) name_list, self.webAddress_history_list = self.load_history_from_database( ) self.listWidget_history.addItems(name_list) listWidget.currentRowChanged.connect(self.listWidget_changed) lineEdit_url.returnPressed.connect(self.lineEdit_enterd) pushButton_copy.clicked.connect(self.pushButton_copy_clicked) webAddress_list = [ address.split('-----')[1].format(text) for address in webAddress_name_list ] self.webAddress_LIST.append(webAddress_list) webName_list = [ address.split('-----')[0] for address in webAddress_name_list ] url = webAddress_list[0] listWidget.addItems(webName_list) browser.setUrl(QUrl(url)) lineEdit_url.setText(url) i = self.tabWidget.addTab(widget, 'loading') browser.urlChanged.connect(lambda qurl, browser=browser: lineEdit_url. setText(qurl.toString())) browser.loadFinished.connect(lambda _, i=i, browser=browser: self. setTabText_and_to_history(i, browser)) self.tabWidget.setCurrentIndex(i) def listWidget_changed(self, i): index = self.tabWidget.currentIndex() browser = self.browser_list[index] url = self.webAddress_LIST[index][i] browser.setUrl(QUrl(url)) lineEdit = self.lineEdit_url_list[index] lineEdit.setText(url)
class H5PlotGUI(QDialog): """The main GUI for H5Plot. From here the SolSets, SolTabs and antennas to plot are selected. """ def __init__(self, h5file, logging_instance, parent=None): super(H5PlotGUI, self).__init__(parent) self.logger = logging_instance self.figures = [] self.h5parm = lh5.h5parm(h5file) self.solset_labels = self.h5parm.getSolsetNames() self.solset = self.h5parm.getSolset('sol000') self.soltab_labels = self.solset.getSoltabNames() self.soltab = self.solset.getSoltab(self.soltab_labels[0]) self.stations = self.soltab.getValues()[1]['ant'] self.refant = 'CS001HBA0' self.wrapphase = True self.stcache = SoltabCache(self.soltab.getValues(), self.soltab.getAxesNames()) rvals, raxes = reorder_soltab(self.soltab) self.stcache.update(rvals, raxes) self.move(300, 300) self.setWindowTitle('H5Plot') self.solset_label = QLabel('SolSet: ') self.solset_picker = QComboBox() for l in self.solset_labels: self.solset_picker.addItem(l) self.solset_picker.activated.connect(self._solset_picker_event) self.soltab_label_y = QLabel('Plot ') self.soltab_label_x = QLabel(' vs ') self.soltab_picker = QComboBox() for l in self.soltab_labels: self.soltab_picker.addItem(l) self.soltab_picker.activated.connect(self._soltab_picker_event) self.axis_picker = QComboBox() self.axis_picker.addItems(['time', 'freq']) self.axis_picker.activated.connect(self._axis_picker_event) self.axis = 'time' self.refant_label = QLabel('Ref. Ant. ') self.refant_picker = QComboBox() self.refant_picker.addItems(self.stations) self.refant_picker.activated.connect(self._refant_picker_event) self.phasewrap_box = QCheckBox('Wrap Phases') self.phasewrap_box.setChecked(True) self.phasewrap_box.setEnabled(False) self.phasewrap_box.stateChanged.connect(self._phasewrap_event) self.plot_button = QPushButton('Plot') self.plot_button.clicked.connect(self._plot_button_event) self.station_picker = QListWidget() self.station_picker.addItems(self.stations) self.station_picker.setCurrentRow(0) plot_layout = QGridLayout() plot_layout.addWidget(self.soltab_label_y, 0, 0) plot_layout.addWidget(self.soltab_picker, 0, 1) plot_layout.addWidget(self.soltab_label_x, 0, 2) plot_layout.addWidget(self.axis_picker, 0, 3) plot_layout.addWidget(self.refant_label, 1, 0) plot_layout.addWidget(self.refant_picker, 1, 1) plot_layout.addWidget(self.phasewrap_box, 1, 3) layout = QFormLayout(self) layout.addRow(self.solset_label, self.solset_picker) layout.addRow(plot_layout) layout.addRow(self.plot_button) layout.addRow(self.station_picker) def _axis_picker_event(self): """Callback function for when the x-axis is changed. Sets the `axis` attribute to the selected axis """ self.logger.debug('Axis changed to: ' + self.axis_picker.currentText()) self.axis = self.axis_picker.currentText() def closeEvent(self, event): self.logger.info('Closing all open figures before exiting.') plt.close('all') event.accept() def _refant_picker_event(self): self.logger.debug('Reference antenna changed to: ' + self.refant_picker.currentText()) self.refant = self.refant_picker.currentText() def _solset_picker_event(self): """Callback function for when the SolSet is changed. Sets the `solset` attribute. """ self.logger.debug('Solset changed to: ' + self.solset_picker.currentText()) self.solset = self.h5parm.getSolset(self.solset_picker.currentText()) self.soltab_labels = self.solset.getSoltabNames() self.soltab_picker.clear() for l in self.soltab_labels: self.soltab_picker.addItem(l) self._soltab_picker_event() def _soltab_picker_event(self): """Callback function for when the SolTab is changed. Sets the `soltab` attribute. """ self.logger.debug('Soltab changed to: ' + self.soltab_picker.currentText()) self.soltab = self.solset.getSoltab(self.soltab_picker.currentText()) rvals, raxes = reorder_soltab(self.soltab) self.stcache.update(rvals, raxes) def _phasewrap_event(self): self.logger.debug('Phase wrapping changed to ' + str(self.phasewrap_box.isChecked())) self.wrapphase = self.phasewrap_box.isChecked() def _plot_button_event(self): """Callback function for when the plot button is pressed. Calls the `plot` function subsecquently. """ self.logger.debug('Plotting button pressed.') self.plot(labels=(self.axis, self.soltab.name)) def plot(self, labels=('x-axis', 'y-axis'), limits=([None, None], [None, None])): self.logger.info('Plotting ' + self.soltab.name + ' vs ' + self.axis + \ ' for ' + self.solset.name) antenna = self.station_picker.currentRow() refantenna = self.refant_picker.currentIndex() # Values have shape (timestamps, frequencies, antennas, polarizations, directions). values = self.stcache.values[0] if (('rotationmeasure' in self.soltab.name) or ('RMextract' in self.soltab.name) or ('clock' in self.soltab.name)) and (self.axis == 'freq'): self.logger.warning( 'Rotation Measure does not support frequency axis! Switch to time instead.' ) return else: x_axis = self.stcache.values[1][self.axis] st_type = self.soltab.getType() print(st_type) fig = plt.figure() ax = fig.add_subplot(111) ax.set_title(self.stations[antenna]) if self.axis == 'time': if 'rotationmeasure' in self.soltab.name: y_axis = values[:, antenna] ax.plot(x_axis, y_axis) elif ('pol' in self.stcache.axes) and ('dir' in self.stcache.axes): if st_type == 'phase': ax.set_ylim(-np.pi, np.pi) # Plot phase-like quantities w.r.t. to a reference antenna. y_axis = values[:, 0, antenna, :, 0] - values[:, 0, refantenna, :, 0] if self.wrapphase: y_axis = wrap_phase(y_axis) elif (st_type == 'clock') or (st_type == 'rotationmeasure'): y_axis = values[:, antenna] else: y_axis = values[:, 0, antenna, :, 0] for i, y in enumerate(y_axis): ax.plot(x_axis, y[:, i], 'h', label=self.stcache.values[1]['pol'][i]) elif 'pol' in self.stcache.axes: if st_type == 'phase': ax.set_ylim(-np.pi, np.pi) # Plot phase-like quantities w.r.t. to a reference antenna. y_axis = values[:, 0, antenna, :] - values[:, 0, refantenna, :] if self.wrapphase: y_axis = wrap_phase(y_axis) elif (st_type == 'clock') or (st_type == 'rotationmeasure'): y_axis = values[:, antenna] else: y_axis = values[:, 0, antenna, :] for i in range(y_axis.shape[1]): ax.plot(x_axis, y_axis[:, i], 'h', label=self.stcache.values[1]['pol'][i]) elif 'dir' in self.stcache.axes: if st_type == 'phase': ax.set_ylim(-np.pi, np.pi) # Plot phase-like quantities w.r.t. to a reference antenna. y_axis = values[:, 0, antenna, 0] - values[:, 0, refantenna, 0] if self.wrapphase: y_axis = wrap_phase(y_axis) elif (st_type == 'clock') or (st_type == 'rotationmeasure'): y_axis = values[:, antenna] else: y_axis = values[:, 0, antenna, 0] ax.plot(x_axis, y_axis[:, i], 'h') elif ('pol' not in self.stcache.axes) and ('dir' not in self.stcache.axes): if (st_type == 'clock') or (st_type == 'rotationmeasure'): y_axis = values[:, antenna] else: y_axis = values[:, 0, antenna] ax.plot(x_axis, y_axis) elif self.axis == 'freq': if ('rotationmeasure' in self.soltab.name) or ('clock' in self.soltab.name): self.logger.warning( 'Rotation Measure does not support frequency axis! Switch to time instead.' ) if ('pol' in self.stcache.axes) and ('dir' in self.stcache.axes): if st_type == 'phase': ax.set_ylim(-np.pi, np.pi) # Plot phase-like quantities w.r.t. to a reference antenna. y_axis = values[0, :, antenna, :, 0] - values[0, :, refantenna, :, 0] if self.wrapphase: y_axis = wrap_phase(y_axis) else: y_axis = values[0, :, antenna, :, 0] for i, y in enumerate(y_axis): ax.plot(x_axis, y[:, i]) elif 'pol' in self.stcache.axes: if st_type == 'phase': ax.set_ylim(-np.pi, np.pi) # Plot phase-like quantities w.r.t. to a reference antenna. y_axis = values[0, :, antenna, :] - values[0, :, refantenna, :] if self.wrapphase: y_axis = wrap_phase(y_axis) else: y_axis = values[0, :, antenna, :] for i in range(y_axis.shape[1]): ax.plot(x_axis, y_axis[:, i], 'h', label=self.stcache.values[1]['pol'][i]) elif 'dir' in self.stcache.axes: if st_type == 'phase': ax.set_ylim(-np.pi, np.pi) # Plot phase-like quantities w.r.t. to a reference antenna. y_axis = values[0, :, antenna, 0] - values[0, :, refantenna, 0] if self.wrapphase: y_axis = wrap_phase(y_axis) else: y_axis = values[0, :, antenna, 0] elif ('pol' not in self.stcache.axes) and ('dir' not in self.stcache.axes): y_axis = values[0, :, antenna] ax.plot(x_axis, y_axis) ax.set(xlabel=self.axis, ylabel=labels[1], xlim=limits[0], ylim=limits[1]) if ax.get_legend_handles_labels()[1]: ax.legend() self.figures.append(fig) fig.show()
def createMissionGroupBox(self): # 1. Missions and instruments group of GUI def button1_find_datasets(): title = "Find Datasets" self.dataset_box.clear() self.file_box.clear() mission_list = [ item.text() for item in self.mission_box.selectedItems() ] instrument_list = [ item.text() for item in self.instrument_box.selectedItems() ] if len(mission_list) < 1 or len(instrument_list) < 1: msg = "Please select at least one mission and one instrument." show_my_message(title, msg) return 0 datasets = self.cda.get_datasets(mission_list, instrument_list) datalen = len(datasets) if datalen < 1: msg = "No datasets were found with these parameters." show_my_message(title, msg) return 0 elif datalen > 50: msg = "Number of datasets found: " + str(datalen) msg += "\nOnly 50 will be shown." show_my_message(title, msg) self.mission_selected.setText(str(mission_list)) self.instrument_selected.setText(str(instrument_list)) self.dataset_box.addItems(datasets[:50]) # Missions group GUI elements self.missionGroupBox = QGroupBox("Missions and Instruments") label1 = QLabel("Mission Groups:") list1 = QListWidget(self) list1.setSelectionMode(QListWidget.MultiSelection) list1.setMinimumHeight(50) list1.setMinimumWidth(400) list1.addItems(self.cda.get_observatories()) self.mission_box = list1 label2 = QLabel("Instrument Types:") list2 = QListWidget(self) list2.setSelectionMode(QListWidget.MultiSelection) list2.setMinimumHeight(50) list2.setMinimumWidth(400) list2.addItems(self.cda.get_instruments()) self.instrument_box = list2 label3 = QLabel("Select one or more Mission Group(s) and one" + " or more Instrument Type(s) and press:") button1 = QPushButton("1. Find Datasets") button1.setStyleSheet(self.button_css) button1.clicked.connect(button1_find_datasets) # Create the layout and add GUI elements # row, column, rowSpan, columnSpan layout = QGridLayout() layout.addWidget(label1, 0, 0) layout.addWidget(label2, 0, 1) layout.addWidget(list1, 1, 0) layout.addWidget(list2, 1, 1) layout.addWidget(label3, 2, 0, 1, 1) layout.addWidget(button1, 2, 1, 1, 1) self.missionGroupBox.setLayout(layout)
class Example(QWidget): # Adding signals externalSignal = QtCore.pyqtSignal([str]) direxternalSignal = QtCore.pyqtSignal([str]) listpathSignal = QtCore.pyqtSignal([str]) listpath31MaxSignal = QtCore.pyqtSignal([int]) itemDoubleClickedSignal = QtCore.pyqtSignal([int]) listpathnextSignal = QtCore.pyqtSignal([str]) def __init__(self): super().__init__() self.initUI() self.buttonLayout = "" def initUI(self): # defining layouts and components self.vbox = QVBoxLayout() self.buttonLayout = QHBoxLayout() self.listwidget = QListWidget() self.label = QLabel() self.Addbtn = QPushButton("Add") self.Removebtn = QPushButton("Remove") self.Nextbtn = QPushButton("Next") self.Previousbtn = QPushButton("Previous") self.Slider = QSlider(Qt.Horizontal) self.lineEditResult = QLineEdit() self.a = self.listwidget.currentRow() self.b = self.listwidget.count() # adding buttons components to buttonlayout self.buttonLayout.addWidget(self.Addbtn) self.buttonLayout.addWidget(self.Removebtn) # connecting buttons to their resp. functions self.Addbtn.clicked.connect(self.getFile) self.Removebtn.clicked.connect(self.remFile) self.listwidget.itemDoubleClicked.connect(self.itemDoubleClick) self.listwidget.itemClicked.connect(self.itemSingleClick) #self.externalSignal.connect(self.showItem) self.direxternalSignal.connect(self.updateLoad) self.vbox.addWidget(self.listwidget) self.vbox.addWidget(self.label) self.vbox.addLayout(self.buttonLayout) self.setLayout(self.vbox) def getFile(self): self.fnameOpen, filter = QFileDialog.getOpenFileNames( self, 'Open file', 'C:\\', " Image files (*.jpg *.gif *.png *.bmp)") self.files_in_path = [] for f in self.fnameOpen: self.files_in_path.append(f) self.listwidget.addItems(self.files_in_path) self.listwidget.update() self.externalSignal[str].emit(self.listwidget.item(0).text()) self.count = self.listwidget.count() self.listpath31MaxSignal[int].emit(self.count - 1) # removes the selected row displayed in the listwidget def remFile(self): self.a = self.listwidget.currentRow() self.b = self.listwidget.count() #if self.b > 0: if self.a == 0: self.listwidget.takeItem(self.a) if self.b > 1: self.listpathSignal.emit(self.listwidget.currentItem().text()) else: self.listpathSignal.emit('') #self.listpath31MaxSignal[int].emit(0) #self.listpath31MaxSignal[int].emit(self.listwidget.currentRow()) #self.listpathnextSignal[str].emit(self.listwidget.currentItem().text()) print("GRAY 0th row removed, the next highlighted row is " + str(self.listwidget.currentRow())) #print("the highlighted text is " + self.listwidget.currentItem().text() ) # if self.a == -1: self.listwidget.clear() #self.listwidget.takeItem(self.a) print("GRAY 0th row removed, the next highlighted row is " + str(self.listwidget.currentRow())) # #print("GRAY 0th row removed, the next highlighted row is " + str(self.listwidget.currentRow())) # #print("the highlighted text is " + self.listwidget.currentItem().text()) # self.listwidget.takeItem(self.a) else: self.listwidget.takeItem(self.a) self.listwidget.update() #print("Count after removing removing file: "+ str(self.a)) #self.listpath31MaxSignal[int].emit(self.b -1) self.listpath31MaxSignal[int].emit(self.listwidget.currentRow()) self.listpathSignal[str].emit(self.listwidget.currentItem().text()) print("GRAY The current row is " + str(self.listwidget.currentRow()) + " the highlighted text is " + self.listwidget.currentItem().text()) self.listpath31MaxSignal[int].emit(max(self.listwidget.count() - 1, 0)) @pyqtSlot() def NextFile(self): self.a = self.listwidget.currentRow() self.b = self.listwidget.count() if self.b == 0: return if self.a == (self.b - 1): self.listwidget.setCurrentItem(self.listwidget.item(0)) self.listwidget.setFocus() self.listpathnextSignal[str].emit( self.listwidget.currentItem().text()) self.itemDoubleClickedSignal[int].emit( self.listwidget.currentRow()) else: self.listwidget.setCurrentItem(self.listwidget.item(self.a + 1)) self.listwidget.setFocus() self.listpathnextSignal[str].emit( self.listwidget.currentItem().text()) print(self.listwidget.currentRow()) self.itemDoubleClickedSignal[int].emit( self.listwidget.currentRow()) @pyqtSlot() def PreviousFile(self): self.a = self.listwidget.currentRow() self.b = self.listwidget.count() if self.a == 0 or self.a == -1: self.listwidget.setCurrentItem(self.listwidget.item(self.b - 1)) self.listpathnextSignal[str].emit( self.listwidget.currentItem().text()) self.itemDoubleClickedSignal[int].emit( self.listwidget.currentRow()) #self.Slider.setSliderPosition(self.a) else: d = self.listwidget.setCurrentItem(self.listwidget.item(self.a - 1)) self.listpathnextSignal[str].emit( self.listwidget.currentItem().text()) self.itemDoubleClickedSignal[int].emit( self.listwidget.currentRow()) #self.component3.Slider.setSliderPosition(self.a) @pyqtSlot(int) def intValueToText(self, value): #print("Item clicked in a list: "+ str(self.count)) self.listwidget.item(value).setSelected(True) self.listwidget.setFocus() self.listwidget.setCurrentItem(self.listwidget.item(value)) self.listpathSignal.emit(self.listwidget.item(value).text()) @pyqtSlot(int) def disValue(self, value): print(("The value is: " + str(value))) @pyqtSlot() def itemSingleClick(self): self.externalSignal[str].emit(self.listwidget.currentItem().text()) self.itemDoubleClickedSignal[int].emit(self.listwidget.currentRow()) print("DARK BLUE, Single click: The highlighted item path is: " + self.listwidget.currentItem().text()) @pyqtSlot() def itemDoubleClick(self): self.externalSignal[str].emit(self.listwidget.currentItem().text()) self.itemDoubleClickedSignal[int].emit(self.listwidget.currentRow()) print("DARK BLUE, Double click: The blue highlighted item path is: " + self.listwidget.currentItem().text()) @pyqtSlot() def updateLoad(self): print(self.listwidget.update()) print(self.listwidget.item(0).text()) @pyqtSlot(str) def showItem(self, text): print(text) @pyqtSlot() def dirLoad(self): self.direxternalSignal[str].emit(self.listwidget.item(0).text())
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.textEdit = QTextEdit() self.setCentralWidget(self.textEdit) self.createActions() self.createMenus() self.createToolBars() self.createStatusBar() self.createDockWindows() self.setWindowTitle("Dock Widgets") self.newLetter() def newLetter(self): self.textEdit.clear() cursor = self.textEdit.textCursor() cursor.movePosition(QTextCursor.Start) topFrame = cursor.currentFrame() topFrameFormat = topFrame.frameFormat() topFrameFormat.setPadding(16) topFrame.setFrameFormat(topFrameFormat) textFormat = QTextCharFormat() boldFormat = QTextCharFormat() boldFormat.setFontWeight(QFont.Bold) italicFormat = QTextCharFormat() italicFormat.setFontItalic(True) tableFormat = QTextTableFormat() tableFormat.setBorder(1) tableFormat.setCellPadding(16) tableFormat.setAlignment(Qt.AlignRight) cursor.insertTable(1, 1, tableFormat) cursor.insertText("The Firm", boldFormat) cursor.insertBlock() cursor.insertText("321 City Street", textFormat) cursor.insertBlock() cursor.insertText("Industry Park") cursor.insertBlock() cursor.insertText("Some Country") cursor.setPosition(topFrame.lastPosition()) cursor.insertText(QDate.currentDate().toString("d MMMM yyyy"), textFormat) cursor.insertBlock() cursor.insertBlock() cursor.insertText("Dear ", textFormat) cursor.insertText("NAME", italicFormat) cursor.insertText(",", textFormat) for i in range(3): cursor.insertBlock() cursor.insertText("Yours sincerely,", textFormat) for i in range(3): cursor.insertBlock() cursor.insertText("The Boss", textFormat) cursor.insertBlock() cursor.insertText("ADDRESS", italicFormat) def print_(self): document = self.textEdit.document() printer = QPrinter() dlg = QPrintDialog(printer, self) if dlg.exec_() != QDialog.Accepted: return document.print_(printer) self.statusBar().showMessage("Ready", 2000) def save(self): filename, _ = QFileDialog.getSaveFileName(self, "Choose a file name", '.', "HTML (*.html *.htm)") if not filename: return file = QFile(filename) if not file.open(QFile.WriteOnly | QFile.Text): QMessageBox.warning(self, "Dock Widgets", "Cannot write file %s:\n%s." % (filename, file.errorString())) return out = QTextStream(file) QApplication.setOverrideCursor(Qt.WaitCursor) out << self.textEdit.toHtml() QApplication.restoreOverrideCursor() self.statusBar().showMessage("Saved '%s'" % filename, 2000) def undo(self): document = self.textEdit.document() document.undo() def insertCustomer(self, customer): if not customer: return customerList = customer.split(', ') document = self.textEdit.document() cursor = document.find('NAME') if not cursor.isNull(): cursor.beginEditBlock() cursor.insertText(customerList[0]) oldcursor = cursor cursor = document.find('ADDRESS') if not cursor.isNull(): for i in customerList[1:]: cursor.insertBlock() cursor.insertText(i) cursor.endEditBlock() else: oldcursor.endEditBlock() def addParagraph(self, paragraph): if not paragraph: return document = self.textEdit.document() cursor = document.find("Yours sincerely,") if cursor.isNull(): return cursor.beginEditBlock() cursor.movePosition(QTextCursor.PreviousBlock, QTextCursor.MoveAnchor, 2) cursor.insertBlock() cursor.insertText(paragraph) cursor.insertBlock() cursor.endEditBlock() def about(self): QMessageBox.about(self, "About Dock Widgets", "The <b>Dock Widgets</b> example demonstrates how to use " "Qt's dock widgets. You can enter your own text, click a " "customer to add a customer name and address, and click " "standard paragraphs to add them.") def createActions(self): self.newLetterAct = QAction(QIcon(':/images/new.png'), "&New Letter", self, shortcut=QKeySequence.New, statusTip="Create a new form letter", triggered=self.newLetter) self.saveAct = QAction(QIcon(':/images/save.png'), "&Save...", self, shortcut=QKeySequence.Save, statusTip="Save the current form letter", triggered=self.save) self.printAct = QAction(QIcon(':/images/print.png'), "&Print...", self, shortcut=QKeySequence.Print, statusTip="Print the current form letter", triggered=self.print_) self.undoAct = QAction(QIcon(':/images/undo.png'), "&Undo", self, shortcut=QKeySequence.Undo, statusTip="Undo the last editing action", triggered=self.undo) self.quitAct = QAction("&Quit", self, shortcut="Ctrl+Q", statusTip="Quit the application", triggered=self.close) self.aboutAct = QAction("&About", self, statusTip="Show the application's About box", triggered=self.about) self.aboutQtAct = QAction("About &Qt", self, statusTip="Show the Qt library's About box", triggered=QApplication.instance().aboutQt) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newLetterAct) self.fileMenu.addAction(self.saveAct) self.fileMenu.addAction(self.printAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.quitAct) self.editMenu = self.menuBar().addMenu("&Edit") self.editMenu.addAction(self.undoAct) self.viewMenu = self.menuBar().addMenu("&View") self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) def createToolBars(self): self.fileToolBar = self.addToolBar("File") self.fileToolBar.addAction(self.newLetterAct) self.fileToolBar.addAction(self.saveAct) self.fileToolBar.addAction(self.printAct) self.editToolBar = self.addToolBar("Edit") self.editToolBar.addAction(self.undoAct) def createStatusBar(self): self.statusBar().showMessage("Ready") def createDockWindows(self): dock = QDockWidget("Customers", self) dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.customerList = QListWidget(dock) self.customerList.addItems(( "John Doe, Harmony Enterprises, 12 Lakeside, Ambleton", "Jane Doe, Memorabilia, 23 Watersedge, Beaton", "Tammy Shea, Tiblanka, 38 Sea Views, Carlton", "Tim Sheen, Caraba Gifts, 48 Ocean Way, Deal", "Sol Harvey, Chicos Coffee, 53 New Springs, Eccleston", "Sally Hobart, Tiroli Tea, 67 Long River, Fedula")) dock.setWidget(self.customerList) self.addDockWidget(Qt.RightDockWidgetArea, dock) self.viewMenu.addAction(dock.toggleViewAction()) dock = QDockWidget("Paragraphs", self) self.paragraphsList = QListWidget(dock) self.paragraphsList.addItems(( "Thank you for your payment which we have received today.", "Your order has been dispatched and should be with you within " "28 days.", "We have dispatched those items that were in stock. The rest of " "your order will be dispatched once all the remaining items " "have arrived at our warehouse. No additional shipping " "charges will be made.", "You made a small overpayment (less than $5) which we will keep " "on account for you, or return at your request.", "You made a small underpayment (less than $1), but we have sent " "your order anyway. We'll add this underpayment to your next " "bill.", "Unfortunately you did not send enough money. Please remit an " "additional $. Your order will be dispatched as soon as the " "complete amount has been received.", "You made an overpayment (more than $5). Do you wish to buy more " "items, or should we return the excess to you?")) dock.setWidget(self.paragraphsList) self.addDockWidget(Qt.RightDockWidgetArea, dock) self.viewMenu.addAction(dock.toggleViewAction()) self.customerList.currentTextChanged.connect(self.insertCustomer) self.paragraphsList.currentTextChanged.connect(self.addParagraph)
class ProfilesLoader(QDialog): def __init__(self, load_func, create_func, save_func, profiles, parent=None): super(ProfilesLoader, self).__init__(self, parent, Qt.Dialog) self.setWindowTitle(_translate("ProfilesLoader", "Profile Manager")) self.setMinimumWidth(400) self._profiles = profiles self.load_function = load_func self.create_function = create_func self.save_function = save_func self.ide = parent vbox = QVBoxLayout(self) vbox.addWidget(QLabel(_translate("ProfilesLoader", "Save your opened files and projects " "into a profile and change really" "quick between projects and" "files sessions.\n This allows you to " "save your working environment, " "keep working in another\n" "project and then go back " "exactly where you left."))) self.profileList = QListWidget() self.profileList.addItems([key for key in profiles]) self.profileList.setCurrentRow(0) self.contentList = QListWidget() self.btnDelete = QPushButton(_translate("ProfilesLoader", "Delete Profile")) self.btnDelete.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.btnUpdate = QPushButton(_translate("ProfilesLoader", "Update Profile")) self.btnUpdate.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.btnCreate = QPushButton(_translate("ProfilesLoader", "Create New Profile")) self.btnCreate.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.btnOpen = QPushButton(_translate("ProfilesLoader", "Open Profile")) self.btnOpen.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.btnOpen.setDefault(True) hbox = QHBoxLayout() hbox.addWidget(self.btnDelete) hbox.addWidget(self.btnUpdate) hbox.addWidget(self.btnCreate) hbox.addWidget(self.btnOpen) vbox.addWidget(self.profileList) vbox.addWidget(self.contentList) vbox.addLayout(hbox) self.profileList.itemSelectionChanged.connect(self.load_profile_content) self.btnOpen.clicked['bool'].connect(self.open_profile) self.btnUpdate.clicked['bool'].connect(self.save_profile) self.btnCreate.clicked['bool'].connect(self.create_profile) self.btnDelete.clicked['bool'].connect(self.delete_profile) def load_profile_content(self): item = self.profileList.currentItem() self.contentList.clear() if item is not None: key = item.text() files = [_translate("ProfilesLoader", 'Files:')] + \ [file[0] for file in self._profiles[key][0]] projects = [_translate("ProfilesLoader", 'Projects:')] + self._profiles[key][1] content = files + projects self.contentList.addItems(content) def create_profile(self): profileName = self.create_function() self.ide.Profile = profileName self.close() def save_profile(self): if self.profileList.currentItem(): profileName = self.profileList.currentItem().text() self.save_function(profileName) self.ide.show_status_message(_translate("ProfilesLoader", "Profile %s Updated!") % profileName) self.load_profile_content() def open_profile(self): if self.profileList.currentItem(): key = self.profileList.currentItem().text() self.load_function(key) self.ide.Profile = key self.close() def delete_profile(self): if self.profileList.currentItem(): key = self.profileList.currentItem().text() self._profiles.pop(key) self.profileList.takeItem(self.profileList.currentRow()) self.contentList.clear()
class SearchCity(QDialog): id_signal = pyqtSignal([tuple]) city_signal = pyqtSignal([tuple]) country_signal = pyqtSignal([tuple]) def __init__(self, accurate_url, appid, parent=None): super(SearchCity, self).__init__(parent) self.settings = QSettings() self.delay = 1000 self.search_string = self.tr('Searching...') self.timer = QTimer() self.accurate_url = accurate_url self.suffix = '&type=like&mode=xml' + appid self.layout = QVBoxLayout() self.lineLayout = QHBoxLayout() self.buttonSearch = QPushButton() self.buttonSearch.setIcon(QIcon(':/find')) self.buttonSearch.clicked.connect(self.search) self.line_search = QLineEdit( QCoreApplication.translate('Search city dialogue', 'Start typing the city...', '')) self.line_search.selectAll() self.listWidget = QListWidget() self.status = QLabel() self.lineLayout.addWidget(self.line_search) self.lineLayout.addWidget(self.buttonSearch) self.layout.addLayout(self.lineLayout) self.layout.addWidget(self.listWidget) self.layout.addWidget(self.status) self.buttonLayout = QHBoxLayout() self.buttonLayout.addStretch() self.buttonOk = QPushButton(self.tr('&Ok')) self.buttonOk.setEnabled(False) self.buttonCancel = QPushButton(self.tr('&Cancel')) self.buttonLayout.addWidget(self.buttonOk) self.buttonLayout.addWidget(self.buttonCancel) self.layout.addLayout(self.buttonLayout) self.setMinimumWidth(int(len(self.line_search.text()) * 20)) self.setLayout(self.layout) self.line_search.returnPressed.connect(self.search) self.line_search.textChanged.connect(self.timer_run) self.buttonOk.clicked.connect(self.accept) self.buttonCancel.clicked.connect(self.reject) self.listWidget.itemSelectionChanged.connect(self.buttonCheck) self.listWidget.itemDoubleClicked['QListWidgetItem *'].connect( self.accept) self.restoreGeometry( self.settings.value("SearchCity/Geometry", QByteArray())) self.timer_search = QTimer(self) self.timer_search.timeout.connect(self.search) self.setWindowTitle( QCoreApplication.translate('Window title', 'Find a city', 'City search dialogue')) def timer_run(self): self.timer_search.start(1000) def closeEvent(self, event): self.settings.setValue("SearchCity/Geometry", self.saveGeometry()) def moveEvent(self, event): self.settings.setValue("SearchCity/Geometry", self.saveGeometry()) def resizeEvent(self, event): self.settings.setValue("SearchCity/Geometry", self.saveGeometry()) def buttonCheck(self): '''Enable OK button if an item is selected.''' row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is not None: self.buttonOk.setEnabled(True) def accept(self): row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is not None: selected_city = item.text() city_list = selected_city.split(' - ') for c in range(len(city_list)): city_list[c] = city_list[c].strip() id_ = 'ID', city_list[0] city = 'City', city_list[1] country = 'Country', city_list[2] self.id_signal[tuple].emit(id_) self.city_signal[tuple].emit(city) self.country_signal[tuple].emit(country) QDialog.accept(self) def thread_terminate(self): if hasattr(self, 'workThread'): if self.workThread.isRunning(): self.workThread.terminate() def search(self): self.timer_search.stop() self.city = (self.line_search.text()) self.thread_terminate() if len(self.city) < 3: self.status.setText(self.tr('Please type more than three letters')) return self.lista = [] self.errorStatus = False self.buttonOk.setEnabled(False) self.listWidget.clear() self.status.setText(self.search_string) self.workThread = WorkThread(self.accurate_url, self.city, self.suffix) self.workThread.setTerminationEnabled(True) self.workThread.city_signal['QString'].connect(self.addlist) self.workThread.finished.connect(self.result) self.workThread.error['QString'].connect(self.error) self.workThread.searching['QString'].connect(self.searching) self.workThread.started.connect(self.thread_started) self.timer.singleShot(self.delay, self.threadstart) def searching(self, message): '''Display a status message when searching takes a while''' self.status.setText(message) def thread_started(self): '''Force the "searching" status message''' self.status.setText(self.search_string) def threadstart(self): self.workThread.start() def addlist(self, city): logging.debug('Found: ' + str(city)) if city not in self.lista: self.lista.append(city) self.errorStatus = False def error(self, e): self.delay = 2000 logging.error(e) self.status.setText(e) self.adjustSize() self.errorStatus = True def result(self): if self.errorStatus: return if len(self.line_search.text()) < 3: self.thread_terminate() self.status.clear() return self.delay = 1000 # Clear the listWidget elements from an interrupted thread self.listWidget.clear() self.listWidget.addItems(self.lista) number_cities = len(self.lista) cities_text = '' if number_cities == 0: cities_text = self.tr('No results') elif number_cities == 1: cities_text = self.tr('Found {0} city').format(number_cities) elif number_cities > 1: cities_text = self.tr('Found {0} cities').format(number_cities) self.status.setText(cities_text)
class SearchCity(QDialog): id_signal = pyqtSignal([tuple]) city_signal = pyqtSignal([tuple]) country_signal = pyqtSignal([tuple]) def __init__(self, accurate_url, appid, parent=None): super(SearchCity, self).__init__(parent) self.settings = QSettings() self.delay = 1000 self.search_string = self.tr('Searching...') self.timer = QTimer() self.accurate_url = accurate_url self.suffix = '&type=like&mode=xml' + appid self.layout = QVBoxLayout() self.lineLayout = QHBoxLayout() self.buttonSearch = QPushButton() self.buttonSearch.setIcon(QIcon.fromTheme("edit-find", QIcon(':/find'))) self.buttonSearch.setToolTip( QCoreApplication.translate( 'Search city button Tooltip', 'Search city', 'Search for the given place' ) ) self.buttonSearch.clicked.connect(self.search) self.buttonMyLocation = QPushButton() self.buttonMyLocation.setIcon(QIcon.fromTheme("applications-geography", QIcon(':/mylocation'))) self.buttonMyLocation.setToolTip( QCoreApplication.translate( 'Search by geolocalisation button tooltip', 'Find my location', 'Automatic search of my place' ) ) self.buttonMyLocation.clicked.connect(self.myLocation) self.line_search = QLineEdit( QCoreApplication.translate( 'Search city dialogue', 'Start typing the city or the geographic ' 'coordinates "latitude, longitude"', 'Default message in the search field' ) ) self.line_search.selectAll() self.listWidget = QListWidget() self.status = QLabel() self.lineLayout.addWidget(self.line_search) self.lineLayout.addWidget(self.buttonSearch) self.lineLayout.addWidget(self.buttonMyLocation) self.layout.addLayout(self.lineLayout) self.layout.addWidget(self.listWidget) self.layout.addWidget(self.status) self.buttonLayout = QHBoxLayout() self.buttonLayout.addStretch() self.buttonOk = QPushButton(self.tr('&Ok')) self.buttonOk.setEnabled(False) self.buttonCancel = QPushButton(self.tr('&Cancel')) self.buttonLayout.addWidget(self.buttonOk) self.buttonLayout.addWidget(self.buttonCancel) self.layout.addLayout(self.buttonLayout) self.setMinimumWidth(800) self.setLayout(self.layout) self.line_search.returnPressed.connect(self.search) self.line_search.textChanged.connect(self.timer_run) self.buttonOk.clicked.connect(self.accept) self.buttonCancel.clicked.connect(self.reject) self.listWidget.itemSelectionChanged.connect(self.buttonCheck) self.listWidget.itemDoubleClicked['QListWidgetItem *'].connect(self.accept) self.restoreGeometry( self.settings.value("SearchCity/Geometry", QByteArray()) ) self.timer_search = QTimer(self) self.timer_search.timeout.connect(self.search) self.setWindowTitle( QCoreApplication.translate( 'Window title', 'Find a city', 'City search dialogue' ) ) self.status.setText( 'ℹ ' + QCoreApplication.translate( 'Status message', 'Click on "Find my Location" button for automatic geolocation', 'City search dialogue' ) ) def timer_run(self): self.timer_search.start(1000) def closeEvent(self, event): self.settings.setValue( "SearchCity/Geometry", self.saveGeometry() ) def moveEvent(self, event): self.settings.setValue( "SearchCity/Geometry", self.saveGeometry() ) def resizeEvent(self, event): self.settings.setValue( "SearchCity/Geometry", self.saveGeometry() ) def buttonCheck(self): '''Enable OK button if an item is selected.''' row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is not None: self.buttonOk.setEnabled(True) def accept(self): row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is not None: selected_city = item.text() city_list = selected_city.split(' - ') for c in range(len(city_list)): city_list[c] = city_list[c].strip() id_ = 'ID', city_list[0] city = 'City', city_list[1] country = 'Country', city_list[2] self.id_signal[tuple].emit(id_) self.city_signal[tuple].emit(city) self.country_signal[tuple].emit(country) QDialog.accept(self) def thread_terminate(self): if hasattr(self, 'workThread'): if self.workThread.isRunning(): self.workThread.terminate() def myLocation(self): locFound = False loc = QCoreApplication.translate( 'Search city', 'N/A', 'Inserted in search field when the automatic' 'geolocalisation is not available' ) try: page = urllib.request.urlopen('http://ipinfo.io/json', timeout=5) rep = page.read().decode('utf-8') locdic = json.loads(rep) loc = locdic['loc'] locFound = True except (KeyError, urllib.error.HTTPError, timeout) as e: locFound = False logging.critical( 'Error fetching geolocation from http://ipinfo.io/json: ' + str(e) ) if locFound is False: try: data = str(urllib.request.urlopen('http://checkip.dyndns.com/', timeout=5).read()) myip = re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1) url = ( 'http://api.ipstack.com/{}?access_key=1f5f4144cd87a4eda32832dad469b586' .format(myip) ) page = urllib.request.urlopen(url, timeout=5) rep = page.read().decode('utf-8') locdic = json.loads(rep) loc = str(locdic['latitude']) + ',' + str(locdic['longitude']) except (KeyError, urllib.error.HTTPError, timeout) as e: logging.critical( 'Error fetching geolocation from {}: '.format(url) + str(e) ) self.line_search.setText(loc) def search(self): self.timer_search.stop() self.city = (self.line_search.text()) self.thread_terminate() if len(self.city) < 3: self.status.setText( QCoreApplication.translate( 'SearchCity window', 'Please type more than three characters', 'Message in the statusbar' ) ) return self.lista = [] self.errorStatus = False self.buttonOk.setEnabled(False) self.listWidget.clear() self.status.setText(self.search_string) self.workThread = WorkThread(self.accurate_url, self.city, self.suffix) self.workThread.setTerminationEnabled(True) self.workThread.city_signal['QString'].connect(self.addlist) self.workThread.finished.connect(self.result) self.workThread.error['QString'].connect(self.error) self.workThread.searching['QString'].connect(self.searching) self.workThread.started.connect(self.thread_started) self.timer.singleShot(self.delay, self.threadstart) def searching(self, message): '''Display a status message when searching takes a while''' self.status.setText(message) def thread_started(self): '''Force the "searching" status message''' self.status.setText(self.search_string) def threadstart(self): self.workThread.start() def addlist(self, city): logging.debug('Found: ' + str(city)) if city not in self.lista: self.lista.append(city) self.errorStatus = False def error(self, e): self.delay = 2000 logging.error(e) self.status.setText(e) self.adjustSize() self.errorStatus = True def result(self): if self.errorStatus: return if len(self.line_search.text()) < 3: self.thread_terminate() self.status.clear() return self.delay = 1000 # Clear the listWidget elements from an interrupted thread self.listWidget.clear() self.listWidget.addItems(self.lista) number_cities = len(self.lista) cities_text = '' if number_cities == 0: cities_text = self.tr('No results') elif number_cities == 1: cities_text = self.tr('Found {0} city').format(number_cities) elif number_cities > 1: cities_text = self.tr('Found {0} cities').format(number_cities) self.status.setText(cities_text)
class PugdebugFileSearchWindow(QDialog): def __init__(self, parent): super(PugdebugFileSearchWindow, self).__init__(parent) self.parent = parent self.setWindowTitle("Search for files ...") self.timer = QTimer() self.timer.setSingleShot(True) self.timer.timeout.connect(self.search_files) self.setup_layout() self.resize(500, 250) def exec(self): self.project_root = settings.value('project/' + projects.active() + '/path/project_root') self.file_search = PugdebugFileSearch(self, self.project_root) super(PugdebugFileSearchWindow, self).exec() def setup_layout(self): self.file_name = PugdebugSearchFileLineEdit(self) self.file_name.textEdited.connect(self.start_timer) self.file_name.returnPressed.connect(self.select_file) self.file_name.up_or_down_pressed_signal.connect(self.select_index) self.files = QListWidget() self.files.setSelectionMode(QAbstractItemView.SingleSelection) self.files.itemActivated.connect(self.file_selected) search_layout = QFormLayout() search_layout.addRow("Search for:", self.file_name) box_layout = QVBoxLayout() box_layout.addLayout(search_layout) box_layout.addWidget(self.files) self.setLayout(box_layout) def start_timer(self, text): self.timer.start(500) def search_files(self): self.files.clear() files = self.file_search.search(self.file_name.text()) self.files.addItems(files) self.files.setCurrentRow(0) def select_file(self): selected_item = self.files.currentItem() self.file_selected(selected_item) def select_index(self, direction): current_index = self.files.currentRow() next_index = current_index max_index = self.files.count() - 1 if direction == 'up' and current_index > 0: next_index = current_index - 1 elif direction == 'down' and current_index < max_index: next_index = current_index + 1 self.files.setCurrentRow(next_index) def file_selected(self, item): path = item.data(Qt.DisplayRole) full_path = "%s/%s" % (self.project_root, path) self.parent.search_file_selected_signal.emit(full_path) self.accept()
class FindDialog(QDialog): alphabetical = [ dict(type="alphabetical", allowPseudoUnicode=True) ] def __init__(self, currentGlyph, parent=None): super().__init__(parent) self.setWindowModality(Qt.WindowModal) self.setWindowTitle(self.tr("Find…")) self._sortedGlyphNames = currentGlyph.font.unicodeData.sortGlyphNames( currentGlyph.layer.keys(), self.alphabetical) layout = QGridLayout(self) self.glyphLabel = QLabel(self.tr("Glyph:"), self) self.glyphEdit = QLineEdit(self) self.glyphEdit.textChanged.connect(self.updateGlyphList) self.glyphEdit.event = self.lineEvent self.glyphEdit.keyPressEvent = self.lineKeyPressEvent self.beginsWithBox = QRadioButton(self.tr("Begins with"), self) self.containsBox = QRadioButton(self.tr("Contains"), self) self.beginsWithBox.setChecked(True) self.beginsWithBox.toggled.connect(self.updateGlyphList) self.glyphList = QListWidget(self) self.glyphList.itemDoubleClicked.connect(self.accept) buttonBox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) l = 0 layout.addWidget(self.glyphLabel, l, 0, 1, 2) layout.addWidget(self.glyphEdit, l, 2, 1, 4) l += 1 layout.addWidget(self.beginsWithBox, l, 0, 1, 3) layout.addWidget(self.containsBox, l, 3, 1, 3) l += 1 layout.addWidget(self.glyphList, l, 0, 1, 6) l += 1 layout.addWidget(buttonBox, l, 0, 1, 6) self.setLayout(layout) self.updateGlyphList() def lineEvent(self, event): if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab: if self.beginsWithBox.isChecked(): self.containsBox.toggle() else: self.beginsWithBox.toggle() return True else: return QLineEdit.event(self.glyphEdit, event) def lineKeyPressEvent(self, event): key = event.key() if key == Qt.Key_Up or key == Qt.Key_Down: self.glyphList.keyPressEvent(event) else: QLineEdit.keyPressEvent(self.glyphEdit, event) def updateGlyphList(self): beginsWith = self.beginsWithBox.isChecked() self.glyphList.clear() if not self.glyphEdit.isModified(): self.glyphList.addItems(self._sortedGlyphNames) else: text = self.glyphEdit.text() if beginsWith: glyphs = [glyphName for glyphName in self._sortedGlyphNames if glyphName and glyphName.startswith(text)] else: glyphs = [glyphName for glyphName in self._sortedGlyphNames if glyphName and text in glyphName] self.glyphList.addItems(glyphs) self.glyphList.setCurrentRow(0) @classmethod def getNewGlyph(cls, parent, currentGlyph): dialog = cls(currentGlyph, parent) result = dialog.exec_() currentItem = dialog.glyphList.currentItem() newGlyph = None if currentItem is not None: newGlyphName = currentItem.text() if newGlyphName in currentGlyph.layer: newGlyph = currentGlyph.layer[newGlyphName] return (newGlyph, result)
class ParameterInputDialog(QDialog): def __init__(self, paramDict, title="Input Parameters", helpText=None, lists=None): try: super(ParameterInputDialog, self).__init__() self.setWindowTitle(title) #Hide ? help button self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint) #Hide top right hand corner X close button self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowCloseButtonHint) QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel #OK and Cancel button #QBtn = QDialogButtonBox.Ok #OK button only self.buttonBox = QDialogButtonBox(QBtn) self.buttonBox.accepted.connect(self.accept) #OK button self.buttonBox.rejected.connect(self.close) #Cancel button self.closeDialog = False self.layout = QFormLayout() if helpText: self.helpTextLbl = QLabel("<H4>" + helpText + "</H4>") self.helpTextLbl.setWordWrap(True) self.layout.addRow(self.helpTextLbl) self.listWidget = [] listCounter = 0 for key in paramDict: #paramType = paramDict[key].lower() paramType, value1, value2, value3 = self.getParamData( paramDict[key].lower()) if paramType not in ("integer", "float", "string", "dropdownlist", "listview"): #This unit test is for developers who mistype the above 3 parameter #types when they are developing new WEASEL tools that need #an input dialog raise IncorrectParameterTypeError if paramType == "integer": self.input = QSpinBox() if value2: self.input.setMinimum(int(value2)) if value3: self.input.setMaximum(int(value3)) if value1: self.input.setValue(int(value1)) elif paramType == "float": self.input = QDoubleSpinBox() if value2: self.input.setMinimum(float(value2)) if value3: self.input.setMaximum(float(value3)) if value1: self.input.setValue(float(value1)) elif paramType == "string": self.input = QLineEdit() if key == "Password": self.input.setEchoMode(QLineEdit.Password) if value1: self.input.setText(value1) else: self.input.setPlaceholderText("Enter your text") #uncomment to set an input mask #self.input.setInputMask('000.000.000.000;_') elif paramType == "dropdownlist": self.input = QComboBox() self.input.addItems(lists[listCounter]) listCounter += 1 if value1: self.input.setCurrentIndex(int(value1)) elif paramType == "listview": self.input = QListWidget() self.input.setSelectionMode( QAbstractItemView.ExtendedSelection) self.input.addItems(lists[listCounter]) #self.input.setFlags(item.flags() | Qt.ItemIsUserCheckable) #self.input.setCheckState(Qt.Unchecked) # scroll bar scrollBar = QScrollBar(self) # setting vertical scroll bar to it self.input.setVerticalScrollBar(scrollBar) self.input.setMinimumHeight( self.input.sizeHintForColumn(0)) self.input.setMinimumWidth(self.input.sizeHintForColumn(0)) listCounter += 1 self.layout.addRow(key, self.input) self.listWidget.append(self.input) self.layout.addRow("", self.buttonBox) self.setLayout(self.layout) self.exec_() #display input dialog except IncorrectParameterTypeError: str1 = 'Cannot procede because the parameter type for an input field ' str2 = 'in the parameter input dialog is incorrect. ' str3 = chr(34) + paramType + chr(34) + ' was used. ' str4 = 'Permitted types are' + chr(34) + 'integer,' + chr( 34) + 'float' + chr(34) str5 = ' and ' + chr(34) + 'string' + chr( 34) + ' input as strings.' warningString = str1 + str2 + str3 + str4 + str5 print(warningString) logger.info('InputDialog - ' + warningString) QMessageBox().critical(self, "Parameter Input Dialog", warningString, QMessageBox.Ok) except Exception as e: print('Error in class ParameterInputDialog.__init__: ' + str(e)) logger.error('Error in class ParameterInputDialog.__init__: ' + str(e)) def getParamData(self, paramDescription): commaCount = paramDescription.count(',') if commaCount == 0: return paramDescription, None, None, None elif commaCount == 1: paramList = paramDescription.split(",") return paramList[0], paramList[1], None, None elif commaCount == 2: paramList = paramDescription.split(",") return paramList[0], paramList[1], paramList[2], None elif commaCount == 3: paramList = paramDescription.split(",") return paramList[0], paramList[1], paramList[2], paramList[3] def close(self): self.closeDialog = True #Now programmatically click OK to close the dialog self.accept() def closeInputDialog(self): return self.closeDialog def returnListParameterValues(self): """Returns a list of parameter values as input by the user, in the same as order as the widgets on the input dialog from top most (first item in the list) to the bottom most (last item in the list).""" try: paramList = [] for item in self.listWidget: if isinstance(item, QLineEdit): paramList.append(item.text()) elif isinstance(item, QComboBox): paramList.append(item.currentText()) elif isinstance(item, QListWidget): paramList.append( [itemText.text() for itemText in item.selectedItems()]) else: paramList.append(item.value()) return paramList except Exception as e: print( 'Error in class ParameterInputDialog.returnListParameterValues: ' + str(e)) logger.error( 'Error in class ParameterInputDialog.returnListParameterValues: ' + str(e))
class MDIWindow(QMainWindow): count = 0 def __init__(self): super().__init__() self.data_dict = {} self.mdi = QMdiArea() self.setCentralWidget(self.mdi) # self.mdi.resize(950,950) bar = self.menuBar() self.current_dir = None self.opened_wd_names = [] file = bar.addMenu("File") file.addAction("New") file.addAction("cascade") file.addAction("Tiled") file.triggered[QAction].connect(self.WindowTrig) load = bar.addMenu("Load") load.addAction("2D") load.addAction("3D") load.triggered[QAction].connect(self.dir_open) toolbar = QToolBar() self.addToolBar(toolbar) bw_button_action = QAction('base_wnd', self) bw_button_action.setStatusTip('base window button') bw_button_action.triggered.connect(self.onclicktb) toolbar.addAction(bw_button_action) self.setWindowTitle("MDI Application") self.base_wd = QMdiSubWindow() self.base_wd.setAttribute(Qt.WA_DeleteOnClose, False) self.base_wd.resize(400, 400) self.base_wd.plt_i = pg.PlotItem(labels={ 'left': ('slits', 'degrees'), 'bottom': ('Kin. Energy', 'eV') }) self.base_wd.plt_iv = pg.ImageView(view=self.base_wd.plt_i) self.base_wd.setWidget(self.base_wd.plt_iv) self.base_wd.setWindowTitle("plot window") self.mdi.addSubWindow(self.base_wd) self.base_wd.show() data_DockWidget = QDockWidget('data', self) data_DockWidget.setObjectName(('data window')) data_DockWidget.setAllowedAreas(Qt.RightDockWidgetArea) self.data_list = QListWidget() data_DockWidget.setWidget(self.data_list) self.addDockWidget(Qt.RightDockWidgetArea, data_DockWidget) self.data_list.itemClicked.connect(self.show_data) self.data_list.itemDoubleClicked.connect(self.get_data) self.mdi.subWindowActivated.connect(self.get_data) def WindowTrig(self, p): if p.text() == "New": MDIWindow.count = MDIWindow.count + 1 sub = QMdiSubWindow() sub.setWidget(QTextEdit()) sub.setWindowTitle("Sub Window" + str(MDIWindow.count)) self.mdi.addSubWindow(sub) sub.show() if p.text() == "cascade": self.mdi.cascadeSubWindows() if p.text() == "Tiled": self.mdi.tileSubWindows() def dir_open(self, p): self.current_dir = dlg.File_dlg.openDirNameDialog(self) print(self.current_dir) if p.text() == "2D": print('2D') files_ls = glob.glob(self.current_dir + '/*.ibw') fls = [f[len(self.current_dir) + 1:] for f in files_ls] print(files_ls) self.data_list.addItems(fls) if p.text() == "3D": zip_ls = glob.glob(self.current_dir + '/*.zip') zp = [f[len(self.current_dir) + 1:] for f in zip_ls] print(zp) self.data_list.addItems(zp) def show_data(self, s): print('show data') file_name = s.text() self.data_dict = ut.ibw2dict(self.current_dir + '/' + file_name) e_sc = self.data_dict['E_axis'][1] - self.data_dict['E_axis'][0] a_sc = self.data_dict['A_axis'][1] - self.data_dict['A_axis'][0] e_str = self.data_dict['E_axis'][0] a_str = self.data_dict['A_axis'][0] self.base_wd.plt_i.setRange(xRange=[self.data_dict['E_axis'][0], self.data_dict['E_axis'][-1]], \ yRange=[self.data_dict['A_axis'][0], self.data_dict['A_axis'][-1]], update=True, padding = 0) self.base_wd.plt_i.getViewBox().setLimits(xMin= e_str, xMax = self.data_dict['E_axis'][-1],\ yMin=self.data_dict['A_axis'][0], yMax=self.data_dict['A_axis'][-1]) self.base_wd.plt_iv.setImage( self.data_dict['data'], pos=[self.data_dict['E_axis'][0], self.data_dict['A_axis'][0]], scale=[e_sc, a_sc]) # self.base_wd.plt_iv.ui.histogram.hide() self.base_wd.plt_iv.ui.roiBtn.hide() self.base_wd.plt_iv.ui.menuBtn.hide() def get_data(self, s): print('get data') if isinstance(s, QMdiSubWindow) and str( s.objectName()) in self.opened_wd_names: sub = self.mdi.currentSubWindow() self.data_dict = ut.ibw2dict(self.current_dir + '/' + str(s.objectName())) elif isinstance(s, QListWidgetItem): file_name = s.text() self.opened_wd_names.append(file_name) MDIWindow.count = MDIWindow.count + 1 sub = QMdiSubWindow() sub.resize(550, 550) sub.setWindowTitle(file_name) sub.setObjectName(file_name) self.data_dict = ut.ibw2dict(self.current_dir + '/' + file_name) else: print(isinstance(s, QMdiSubWindow), isinstance(s, QListWidgetItem)) print(type(s)) return e_sc = self.data_dict['E_axis'][1] - self.data_dict['E_axis'][0] a_sc = self.data_dict['A_axis'][1] - self.data_dict['A_axis'][0] e_rg = self.data_dict['E_axis'][-1] - self.data_dict['E_axis'][0] a_rg = self.data_dict['A_axis'][-1] - self.data_dict['A_axis'][0] e_str = self.data_dict['E_axis'][0] a_str = self.data_dict['A_axis'][0] e_end = self.data_dict['E_axis'][-1] a_end = self.data_dict['A_axis'][-1] print(e_str, a_str) print(e_end, a_end) print(e_rg, a_rg) print(e_sc, a_sc) gr_v = pg.GraphicsView() l = pg.GraphicsLayout() gr_v.setCentralWidget(l) sub.setWidget(gr_v) self.mdi.addSubWindow(sub) sub.show() p1 = l.addPlot(x=[1, 2], y=[1, 2], name="Plot1", title="EDC", pen="r", row=0, col=0) # label1 = pg.LabelItem(justify='right') # p1.addItem(label1) plt_i = pg.PlotItem(labels={ 'left': ('slits', 'degrees'), 'bottom': ('Kin. Energy', 'eV') }) plt_i.setRange(xRange=[e_str, e_end], yRange=[a_str, a_end], update=True, padding=0) vb = plt_i.getViewBox() vb.setLimits(xMin=e_str, xMax=e_end, yMin=a_str, yMax=a_end) l.addItem(plt_i, row=1, col=0) img_i = pg.ImageItem(self.data_dict['data'], border=None) qrect = vb.viewRect() img_i.setRect(qrect) vb.addItem(img_i) vb.autoRange() # vb.invertX() vb.invertY() p2 = l.addPlot(x=[1, 2], y=[2, 1], name="Plot2", title="MDC", pen="g", row=1, col=1) # label2 = pg.LabelItem(justify='left') # plt_i.addItem(label2) # cross hair vLine = pg.InfiniteLine(angle=90, movable=False) hLine = pg.InfiniteLine(angle=0, movable=False) p1.addItem(vLine, ignoreBounds=False) p1.addItem(hLine, ignoreBounds=False) vb1 = p1.vb pcv = plt_i.addLine(x=e_end, pen='r') pch = plt_i.addLine(y=a_str, pen='r') # lROI = pg.ROI(((e_str+e_end)/2,a_str), size=(5*e_sc,a_rg)) # vb.addItem(lROI) # slice, coor = lROI.getArrayRegion(self.data_dict['data'], img_i ,returnMappedCoords = True) # print('slice') # sl_sum=np.sum(slice, axis=0) # print(sl_sum[0:10]) # print(type(slice), slice.shape) # print(type(coor), coor.shape) # print(coor[1,0,0:10]) # p2.invertY() # p2.setYLink(plt_i) # p2.plot(y=coor[1,0,:], x=sl_sum) def onMouseMoved(point): p = vb.mapSceneToView(point) pcv.setValue(p.x()) pch.setValue(p.y()) # print(p.x(), p.y()) hROI = pg.ROI((e_str, p.y()), size=(e_rg, 5 * a_sc)) vb.addItem(hROI) hROI.hide() sl, co = hROI.getArrayRegion(self.data_dict['data'], img_i, returnMappedCoords=True) sl_sum = np.sum(sl, axis=1) p1.setXLink(plt_i) p1.plot(x=co[0, :, 0], y=sl_sum, clear=True) vROI = pg.ROI((p.x(), a_str), size=(5 * e_sc, a_rg)) vb.addItem(vROI) vROI.hide() slc, coo = vROI.getArrayRegion(self.data_dict['data'], img_i, returnMappedCoords=True) sl_sum = np.sum(slc, axis=0) p2.invertY() p2.setYLink(plt_i) p2.plot(y=coo[1, 0, :], x=sl_sum, clear=True) # label2.setText("{}-{}".format(p.x(), p.y())) img_i.scene().sigMouseMoved.connect(onMouseMoved) def onclicktb(self): self.base_wd.plt_i = pg.PlotItem(labels={ 'left': ('slits', 'degrees'), 'bottom': ('Kin. Energy', 'eV') }) self.base_wd.plt_iv = pg.ImageView(view=self.base_wd.plt_i) self.base_wd.setWidget(self.base_wd.plt_iv) self.base_wd.show()
class RulesWidget(QWidget): sendCommand = pyqtSignal(str, str) def __init__(self, device, *args, **kwargs): super(RulesWidget, self).__init__(*args, **kwargs) self.device = device self.setWindowTitle("Rules [{}]".format( self.device.p['FriendlyName1'])) self.poll_timer = QTimer() self.poll_timer.timeout.connect(self.poll) self.poll_timer.start(1000) self.vars = [''] * 16 self.var = None self.mems = [''] * 16 self.mem = None self.rts = [0] * 8 self.rt = None fnt_mono = QFont("asd") fnt_mono.setStyleHint(QFont.TypeWriter) tb = Toolbar(iconsize=24, label_position=Qt.ToolButtonTextBesideIcon) vl = VLayout(margin=0, spacing=0) self.cbRule = QComboBox() self.cbRule.setMinimumWidth(100) self.cbRule.addItems(["Rule{}".format(nr + 1) for nr in range(3)]) self.cbRule.currentTextChanged.connect(self.load_rule) tb.addWidget(self.cbRule) self.actEnabled = CheckableAction(QIcon(":/off.png"), "Enabled") self.actEnabled.triggered.connect(self.toggle_rule) self.actOnce = CheckableAction(QIcon(":/once.png"), "Once") self.actOnce.triggered.connect(self.toggle_once) self.actStopOnError = CheckableAction(QIcon(":/stop.png"), "Stop on error") self.actStopOnError.triggered.connect(self.toggle_stop) tb.addActions([self.actEnabled, self.actOnce, self.actStopOnError]) self.cbRule.setFixedHeight( tb.widgetForAction(self.actEnabled).height() + 1) self.actUpload = tb.addAction(QIcon(":/upload.png"), "Upload") self.actUpload.triggered.connect(self.upload_rule) # tb.addSeparator() # self.actLoad = tb.addAction(QIcon(":/open.png"), "Load...") # self.actSave = tb.addAction(QIcon(":/save.png"), "Save...") tb.addSpacer() self.counter = QLabel("Remaining: 511") tb.addWidget(self.counter) vl.addWidget(tb) hl = HLayout(margin=[3, 0, 0, 0]) self.gbTriggers = GroupBoxV("Triggers") self.triggers = QListWidget() self.triggers.setAlternatingRowColors(True) self.gbTriggers.addWidget(self.triggers) self.gbEditor = GroupBoxV("Rule editor") self.editor = QPlainTextEdit() self.editor.setFont(fnt_mono) self.editor.setPlaceholderText("loading...") self.editor.textChanged.connect(self.update_counter) self.gbEditor.addWidget(self.editor) # hl.addWidgets([self.gbTriggers, self.gbEditor]) hl.addWidget(self.gbEditor) self.rules_hl = RuleHighLighter(self.editor.document()) vl_helpers = VLayout(margin=[0, 0, 3, 0]) ###### Polling self.gbPolling = GroupBoxH("Automatic polling") self.pbPollVars = QPushButton("VARs") self.pbPollVars.setCheckable(True) self.pbPollMems = QPushButton("MEMs") self.pbPollMems.setCheckable(True) self.pbPollRTs = QPushButton("RuleTimers") self.pbPollRTs.setCheckable(True) self.gbPolling.addWidgets( [self.pbPollVars, self.pbPollMems, self.pbPollRTs]) ###### VARS # self.gbVars = GroupBoxV("VARs") self.lwVars = QListWidget() self.lwVars.setAlternatingRowColors(True) self.lwVars.addItems( ["VAR{}: <unknown>".format(i) for i in range(1, 17)]) self.lwVars.clicked.connect(self.select_var) self.lwVars.doubleClicked.connect(self.set_var) # self.gbVars.addWidget(self.lwVars) ###### MEMS # self.gbMems = GroupBoxV("MEMs") self.lwMems = QListWidget() self.lwMems.setAlternatingRowColors(True) self.lwMems.addItems( ["MEM{}: <unknown>".format(i) for i in range(1, 17)]) self.lwMems.clicked.connect(self.select_mem) self.lwMems.doubleClicked.connect(self.set_mem) # self.gbMems.addWidget(self.lwMems) ###### RuleTimers # self.gbRTs = GroupBoxV("Rule timers") self.lwRTs = QListWidget() self.lwRTs.setAlternatingRowColors(True) self.lwRTs.addItems( ["RuleTimer{}: <unknown>".format(i) for i in range(1, 9)]) self.lwRTs.clicked.connect(self.select_rt) self.lwRTs.doubleClicked.connect(self.set_rt) # self.gbRTs.addWidget(self.lwRTs) # vl_helpers.addWidgets([self.gbPolling, self.gbVars, self.gbMems, self.gbRTs]) vl_helpers.addWidgets( [self.gbPolling, self.lwVars, self.lwMems, self.lwRTs]) vl_helpers.setStretch(1, 16) vl_helpers.setStretch(2, 16) vl_helpers.setStretch(3, 8) hl.addLayout(vl_helpers) hl.setStretch(0, 3) hl.setStretch(1, 1) # hl.setStretch(2, 1) vl.addLayout(hl) self.setLayout(vl) def load_rule(self, text): self.editor.setPlaceholderText("loading...") self.sendCommand.emit(self.device.cmnd_topic(text), "") def toggle_rule(self, state): self.sendCommand.emit( self.device.cmnd_topic(self.cbRule.currentText()), str(int(state))) def toggle_once(self, state): self.sendCommand.emit( self.device.cmnd_topic(self.cbRule.currentText()), str(4 + int(state))) def toggle_stop(self, state): self.sendCommand.emit( self.device.cmnd_topic(self.cbRule.currentText()), str(8 + int(state))) def clean_rule(self): re_spaces = re.compile(r"\s{2,}") rule = self.editor.toPlainText().replace("\t", " ").replace("\n", " ") rule = re.sub(re_spaces, ' ', rule) return rule def upload_rule(self): rule = self.clean_rule() if len(rule) == 0: rule = '""' self.sendCommand.emit( self.device.cmnd_topic(self.cbRule.currentText()), rule) def update_counter(self): self.counter.setText("Remaining: {}".format(511 - len(self.clean_rule()))) def poll(self): if self.pbPollVars.isChecked(): self.sendCommand.emit(self.device.cmnd_topic("var"), "") if self.pbPollMems.isChecked(): self.sendCommand.emit(self.device.cmnd_topic("mem"), "") if self.pbPollRTs.isChecked(): self.sendCommand.emit(self.device.cmnd_topic("ruletimer"), "") def select_var(self, idx): self.var = idx.row() def set_var(self, idx): curr = self.vars[self.var] new, ok = QInputDialog.getText( self, "Set VAR", "Set VAR{} value. Empty to clear.".format(self.var + 1), text=curr) if ok: if new == '': new = '"' self.sendCommand.emit( self.device.cmnd_topic("var{}".format(self.var + 1)), new) def select_mem(self, idx): self.mem = idx.row() def set_mem(self, idx): curr = self.mems[self.mem] new, ok = QInputDialog.getText( self, "Set mem", "Set mem{} value. Empty to clear.".format(self.mem + 1), text=curr) if ok: if new == '': new = '"' self.sendCommand.emit( self.device.cmnd_topic("mem{}".format(self.mem + 1)), new) def select_rt(self, idx): self.rt = idx.row() def set_rt(self, idx): curr = self.rts[self.rt] new, ok = QInputDialog.getInt(self, "Set ruletimer", "Set ruletimer{} value.".format(self.rt + 1), value=curr) if ok: self.sendCommand.emit( self.device.cmnd_topic("ruletimer{}".format(self.rt + 1)), str(new)) def display_rule(self, payload, rule): rules = payload['Rules'].replace(" on ", "\non ").replace( " do ", " do\n\t").replace(" endon", "\nendon ").rstrip(" ") if len(rules) == 0: self.editor.setPlaceholderText("rule buffer is empty") self.editor.setPlainText(rules) self.actEnabled.setChecked(payload[rule] == "ON") self.actOnce.setChecked(payload['Once'] == 'ON') self.actStopOnError.setChecked(payload['StopOnError'] == 'ON') @pyqtSlot(str, str) def parseMessage(self, topic, msg): if self.device.matches(topic): payload = None if msg.startswith("{"): try: payload = loads(msg) except JSONDecodeError as e: # JSON parse exception means that most likely the rule contains an unescaped JSON payload # TDM will attempt parsing using a regex instead of json.loads() parsed_rule = re.match( r"{\"(?P<rule>Rule(\d))\":\"(?P<enabled>ON|OFF)\",\"Once\":\"(?P<Once>ON|OFF)\",\"StopOnError\":\"(?P<StopOnError>ON|OFF)\",\"Free\":\d+,\"Rules\":\"(?P<Rules>.*?)\"}$", msg, re.IGNORECASE) # modify the resulting matchdict to follow the keys of original JSON payload payload = deepcopy(parsed_rule.groupdict()) rule = payload.pop("rule") payload[rule] = payload.pop("enabled") self.display_rule(payload, rule) else: if payload: keys = list(payload.keys()) fk = keys[0] if self.device.reply == 'RESULT' and fk == "T1" or self.device.reply == "RULETIMER": for i, rt in enumerate(payload.keys()): self.lwRTs.item(i).setText( "RuleTimer{}: {}".format( i + 1, payload[rt])) self.rts[i] = payload[rt] elif self.device.reply == 'RESULT' and fk.startswith( "Var") or self.device.reply.startswith("VAR"): for k, v in payload.items(): row = int(k.replace("Var", "")) - 1 self.lwVars.item(row).setText( "VAR{}: {}".format(row + 1, v)) self.vars[row] = v elif self.device.reply == 'RESULT' and fk.startswith( "Mem") or self.device.reply.startswith("MEM"): for k, v in payload.items(): row = int(k.replace("Mem", "")) - 1 self.lwMems.item(row).setText( "MEM{}: {}".format(row + 1, v)) self.mems[row] = v elif self.device.reply == 'RESULT' and fk.startswith( "Rule") or self.device.reply.startswith( "RULE"): self.display_rule(payload, fk)
class MainWindow(QWidget): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint) # self.setAttribute(Qt.WA_TranslucentBackground) self.resize(900, 700) self.__search_mode = {'fuzzy': 'fuzzy_search', 'precise': 'precise_search', 'reg': 'reg_search'} # self.__pbn_switch_view = None # 创建窗口部件 self.__widget_frame = QLabel() # window title self.__lab_title_fram = QLabel() self.__lab_title = QLabel('搜索辅助工具') self.__lab_title.setAlignment(Qt.AlignCenter) self.__lab_open_tool = QLabel('打开文件方式') self.__ln_open_tool = QLineEdit() self.__pbn_open_tool = QToolButton() self.__pbn_open_tool.setText('选择...') self.__ln_open_tool.setFixedHeight(20) self.__ln_open_tool.setFixedWidth(150) self.__pbn_open_tool.setFixedSize(48, 20) self.__lab_title_fram.setFixedHeight(50) # search mode self.__lab_mode_fram = QLabel() self.__rbn_fuzzy = QRadioButton('模糊搜索') self.__rbn_precise = QRadioButton('精确搜索') self.__rbn_reg = QRadioButton('正则表达式搜索') self.__rbn_fuzzy.setChecked(True) self.__lab_mode_fram.setFixedHeight(22) # search pattern self.__lab_pattern_fram = QLabel() self.__ln_file_name = QLineEdit() self.__ln_file_name.setPlaceholderText('请输入搜索条件或正则表达式......') self.__rbn_reg_Iyes = QRadioButton('区分大小写') self.__rbn_reg_Ino = QRadioButton('不区分大小写') self.__lab_pattern_fram.setFixedHeight(20) # search path self.__lab_path_fram = QLabel() self.__ln_file_path = QLineEdit() self.__ln_file_path.setPlaceholderText('请选择或输入路径......') self.__pbn_file_path = QToolButton() self.__pbn_file_path.setText('浏览...') self.__rbn_search_file = QRadioButton('检索文件名') self.__rbn_search_content = QRadioButton('检索文件内容') self.__pbn_file_path.setFixedSize(48, 20) self.__lab_path_fram.setFixedHeight(20) # search state self.__lab_state_fram = QLabel() self.__lab_state = QLabel('状态:暂无搜索结果!') self.__pbn_search = QPushButton('开始') self.__pbn_stop = QPushButton('停止') self.__pbn_search.setFixedWidth(89) self.__pbn_stop.setFixedWidth(89) self.__lab_state_fram.setFixedHeight(35) # search result self.__tabView = QTabWidget() self.__browser_result = QListWidget() self.__browser_error = QTextBrowser() self.__tabView.addTab(self.__browser_result, '匹配结果') self.__tabView.addTab(self.__browser_error, '错误结果') self.__btn_group_type = QButtonGroup() self.__btn_group_type.addButton(self.__rbn_search_file) self.__btn_group_type.addButton(self.__rbn_search_content) self.__rbn_search_file.setChecked(True) # radiobutton group self.__btn_group_re_I = QButtonGroup() self.__btn_group_re_I.addButton(self.__rbn_reg_Iyes) self.__btn_group_re_I.addButton(self.__rbn_reg_Ino) self.__rbn_reg_Iyes.setChecked(True) # lines ''' self.__line_1 = QFrame() self.__line_1.setFrameStyle(QFrame.HLine | QFrame.Sunken) ''' # 布局 # open tool self.__layout_tool_choose = QHBoxLayout() self.__layout_tool_choose.addWidget(self.__ln_open_tool) self.__layout_tool_choose.addWidget(self.__pbn_open_tool) self.__layout_tool_choose.setSpacing(0) self.__layout_tool_choose.setContentsMargins(0, 0, 0, 0) self.__layout_open_tool = QHBoxLayout() self.__layout_open_tool.addWidget(self.__lab_open_tool) self.__layout_open_tool.addLayout(self.__layout_tool_choose) self.__layout_open_tool.setSpacing(2) # window title self.__layout_title = QHBoxLayout() self.__layout_title.addStretch(5) self.__layout_title.addWidget(self.__lab_title) self.__layout_title.addStretch(1) self.__layout_title.addLayout(self.__layout_open_tool) self.__layout_title.setContentsMargins(0, 0, 0, 20) self.__lab_title_fram.setLayout(self.__layout_title) # search mode self.__layout_search_mode = QHBoxLayout() self.__layout_search_mode.addWidget(self.__rbn_fuzzy) self.__layout_search_mode.addStretch() self.__layout_search_mode.addWidget(self.__rbn_precise) self.__layout_search_mode.addStretch() self.__layout_search_mode.addWidget(self.__rbn_reg) self.__layout_search_mode.setContentsMargins(60, 0, 60, 0) self.__lab_mode_fram.setLayout(self.__layout_search_mode) # search pattern self.__layout_search_reg_I = QHBoxLayout() self.__layout_search_reg_I.addWidget(self.__rbn_reg_Iyes) self.__layout_search_reg_I.addWidget(self.__rbn_reg_Ino) self.__layout_pattern = QHBoxLayout() self.__layout_pattern.addWidget(self.__ln_file_name) self.__layout_pattern.addLayout(self.__layout_search_reg_I) self.__layout_pattern.setContentsMargins(0, 0, 0, 0) self.__lab_pattern_fram.setLayout(self.__layout_pattern) # search path self.__layout_choose_path = QHBoxLayout() self.__layout_choose_path.addWidget(self.__ln_file_path) self.__layout_choose_path.addWidget(self.__pbn_file_path) self.__layout_choose_path.setSpacing(0) self.__layout_path = QHBoxLayout() self.__layout_path.addLayout(self.__layout_choose_path) self.__layout_path.addWidget(self.__rbn_search_file) self.__layout_path.addWidget(self.__rbn_search_content) self.__layout_path.setContentsMargins(0, 0, 0, 0) self.__lab_path_fram.setLayout(self.__layout_path) # search state self.__layout_state = QHBoxLayout() self.__layout_state.addWidget(self.__lab_state) self.__layout_state.addWidget(self.__pbn_search) self.__layout_state.addWidget(self.__pbn_stop) self.__layout_state.setContentsMargins(0, 0, 0, 10) self.__lab_state_fram.setLayout(self.__layout_state) # top layout self.__layout_top = QVBoxLayout() self.__layout_top.addWidget(self.__lab_title_fram) self.__layout_top.addWidget(self.__lab_mode_fram) self.__layout_top.addWidget(self.__lab_pattern_fram) self.__layout_top.addWidget(self.__lab_path_fram) self.__layout_top.addWidget(self.__lab_state_fram) self.__layout_top.addWidget(self.__tabView) self.__layout_top.setSpacing(10) self.__widget_frame.setLayout(self.__layout_top) self.__layout_fram = QGridLayout() self.__layout_fram.addWidget(self.__widget_frame, 0, 0, 1, 1) self.__layout_fram.setContentsMargins(0, 0, 0, 0) self.setLayout(self.__layout_fram) # set object name self.__widget_frame.setObjectName('fram') self.__lab_title.setObjectName('lab_title') self.__ln_open_tool.setObjectName('ln_open_tool') self.__lab_mode_fram.setObjectName('mode_fram') self.__ln_file_name.setObjectName('ln_pattern') self.__ln_file_path.setObjectName('ln_path') self.__lab_state.setObjectName('state') self.__tabView.setObjectName('tabView') self.__browser_result.setObjectName('browser_result') self.__browser_error.setObjectName('browser_error') self.setStyleSheet( '#fram{' 'border-image: url(Images/bg);' '}' '#lab_title{' 'color: white;' 'font-size: 18pt;' '}' '#open_tool{' 'color: black;' '}' '#mode_fram{' # 'border-top: 1px solid rgba(20, 20, 20, 100);' # 'border-bottom: 1px solid rgba(20, 20, 20, 100);' 'background: rgba(0, 0, 0, 40);' '}' '#ln_open_tool, #ln_path{' 'border-top-left-radius: 2px;' 'border-bottom-left-radius: 2px;' '}' '#ln_pattern{' 'border-radius: 2px;' '}' '#state{' 'background: rgba(0, 0, 0, 40);' 'border-radius: 2px;' 'padding: 1px;' 'color: rgb(240, 240, 240);' '}' 'QTabBar::tab {' 'border: 0;' 'width: 90px;' 'height: 20px;' 'margin: 0 2px 0 0;' # top right bottom left # 'border-top-left-radius: 5px;' # 'border-top-right-radius: 5px;' 'color: rgb(200, 255, 255;);' '}' 'QTabBar::tab:selected{' 'background: rgba(25, 0, 0, 40);' 'border-left: 1px solid rgba(255, 255, 255, 200);' 'border-top: 1px solid rgba(255, 255, 255, 200);' 'border-right: 1px solid rgba(255, 255, 255, 200);' '}' 'QTabWidget:pane {' 'border: 1px solid rgba(255, 255, 255, 200);' 'background: rgba(0, 0, 0, 80);' '}' '#browser_result, #browser_error{' 'background: rgba(0, 0, 0, 0);' 'border: 0;' '}' 'QLineEdit{' 'background: rgba(0, 0, 0, 40);' 'border: 1px solid rgba(220, 220, 220, 200);' 'color: white;' 'height: 20px;' '}' 'QPushButton{' 'background: rgba(0, 0, 0, 100);' 'border-radius: 5px;' 'height: 20px;' 'color: white;' '}' 'QPushButton::hover{' 'background: rgba(0, 0, 0, 150);' '}' 'QToolButton{' 'background: rgba(0, 0, 0, 100);' 'color: white;' 'border-top-right-radius: 2px;' 'border-bottom-right-radius: 2px;' '}' 'QToolButton::hover{' 'background: rgba(0, 0, 0, 150);' '}' ) self.__ln_file_name.setFocus() self.__pbn_search.setShortcut(Qt.Key_Return) # 关联 信号/槽 self.__pbn_file_path.clicked.connect(self.choose_path) self.__pbn_search.clicked.connect(self.pbn_search_clicked) self.__pbn_stop.clicked.connect(self.pbn_stop) self.__pbn_open_tool.clicked.connect(self.choose_open_tool) self.__browser_result.doubleClicked.connect(self.listitem_clicked) # 线程间共享数据队列 queue_size = 10000 self.__queue_result = Queue(queue_size) self.__queue_error = Queue(queue_size) # 标记搜索状态 self.__searching = False # 强制结束子线程 self.__thread_killer = False # 重写鼠标按下事件 def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.offset = event.globalPos() - self.pos() # 重写鼠标移动事件 def mouseMoveEvent(self, event): if event.buttons() == Qt.LeftButton: self.move(event.globalPos() - self.offset) # 检测记事本程序 def set_open_tool(self): if platform.architecture() == ('32bit', 'WindowsPE'): possible_dir = ['C:\\Program Files\\Sublime Text 2', 'C:\\Sublime Text 2', 'D:\\Program Files\\Sublime Text 2', 'D:\\Sublime Text 2', 'E:\\Program Files\\Sublime Text 2', 'E:\\Sublime Text 2', 'F:\\Program Files\\Sublime Text 2', 'F:\\Sublime Text 2', 'C:\\Program Files\\Notepad++', 'C:\\notepad++', 'D:\\Program Files\\Notepad++', 'D:\\notepad++', 'E:\\Program Files\\Notepad++', 'E:\\notepad++', 'F:\\Program Files\\Notepad++', 'F:\\notepad++', 'C:\\Windows\\System32'] elif platform.architecture() == ('32bit', 'ELF'): possible_dir = ['/usr/bin'] for rootdir in possible_dir: for root, dirs, files in walk(rootdir): for file in files: if file == 'sublime_text.exe' or file == 'notepad++.exe' or file == 'notepad.exe': self.__ln_open_tool.setText(join(root, file)) return # 搜索文件名 def search_from_filename(self, filepath, filename, mode='fuzzy_search', I=True): # check arguments of searching if filepath == '' or not exists(filepath): return False if mode not in self.__search_mode.values(): return False if filename == '': return False # count count = 0 # fuzzy mode if mode == self.__search_mode['fuzzy']: for root, dirs, files in walk(filepath): for each_file in files: # kill subThread if self.__thread_killer == True: return if filename in each_file: count += 1 self.__lab_state.setText('正在搜索......已搜到 %d 个文件' % count) self.__queue_result.put(join(root, each_file)) self.__tabView.setTabText(0, '匹配结果(%d)' % count) # precise mode elif mode == self.__search_mode['precise']: for root, dirs, files in walk(filepath): for each_file in files: # kill subThread if self.__thread_killer == True: return if filename == splitext(each_file)[0] or filename == each_file: count += 1 self.__lab_state.setText('正在搜索......已搜到 %d 个文件' % count) self.__queue_result.put(join(root, each_file)) self.__tabView.setTabText(0, '匹配结果(%d)' % count) # regular expression mode elif mode == self.__search_mode['reg']: if I: pattern = re.compile(r'%s' % filename) else: pattern = re.compile(r'%s' % filename, re.I) for root, dirs, files in walk(filepath): for each_file in files: # kill subThread if self.__thread_killer == True: return if re.search(pattern, each_file): count += 1 self.__lab_state.setText('正在搜索......已搜到 %d 个文件' % count) self.__queue_result.put(join(root, each_file)) self.__tabView.setTabText(0, '匹配结果(%d)' % count) self.__lab_state.setText('搜索完毕! 共搜到 %d 个文件' % count) # finished self.__searching = False # set serching flag # 搜索文件内容 def search_from_content(self, path, content, mode='fuzzy_search', I=True): if path == '' or not exists(path): return False if mode not in self.__search_mode.values(): return False if content == '': return False pass_file_count = 0 error_number = 0 current_file = '' processing_file = '' match_files_count = 0 if mode == self.__search_mode['reg']: if I: pattern = re.compile(r'%s' % content) else: pattern = re.compile(r'%s' % content, re.I) for root, dirs, files in walk(path): for each_file in [file for file in files if file.endswith('.h') or file.endswith('.cpp') or file.endswith('.cs')]: current_file = join(root, each_file) pass_file_count += 1 self.__lab_state.setText('正在搜索......%s' % current_file) try: for line_number, line in enumerate(open(current_file)): # kill subThread if self.__thread_killer == True: return if re.search(pattern, line): if processing_file != current_file: self.__queue_result.put('\n%s' % current_file) processing_file = current_file match_files_count += 1 self.__queue_result.put('line %s: %s' % (line_number, line.strip())) except Exception as error: self.__queue_error.put("%s\n(%s)\n" % (error, current_file)) pass_file_count -= 1 error_number += 1 continue self.__tabView.setTabText(0, '匹配结果(%d)' % match_files_count) else: for root, dirs, files in walk(path): for each_file in [file for file in files if file.endswith('.h') or file.endswith('.cpp') or file.endswith('.cs') or file.endswith('.txt') or file.endswith('.py')]: current_file = join(root, each_file) pass_file_count += 1 self.__lab_state.setText('正在搜索......%s' % current_file) try: for line_number, line in enumerate(open(current_file)): # kill subThread if self.__thread_killer == True: return if content in line: # 匹配成功 if processing_file != current_file: # 如果是新文件 self.__queue_result.put('\n%s' % current_file) # 文件名入队 processing_file = current_file # 更新文件标记 match_files_count += 1 self.__queue_result.put('line %s: %s' % (line_number, line.strip())) # 匹配行入队 except Exception as error: self.__queue_error.put("%s\n(%s)\n" % (error, current_file)) pass_file_count -= 1 error_number += 1 continue self.__tabView.setTabText(0, '匹配结果(%d)' % match_files_count) # self.__queue_result.put() self.__lab_state.setText('搜索完毕!成功匹配 %d 个文件,处理 %s 个文件,失败 %s 文件。' % (match_files_count, pass_file_count, error_number)) self.__searching = False # 单击选择路径按钮 def choose_path(self): path = QFileDialog.getExistingDirectory() if path != '': path = sep.join(path.split('/')) self.__ln_file_path.setText(path) # 选择打开文件工具 def choose_open_tool(self): path = QFileDialog.getOpenFileName() if path[0] != '': self.__ln_open_tool.setText(path[0]) # 显示搜索结果 def show_search_result(self): """将搜索结果加载到界面,供用户查看和操作""" line_block = [] # 定义临时列表,成批加载,避免刷新频率过高造成界面闪烁 block_size = 10 # 一次性加载的个数 while self.__searching or self.__queue_result.qsize(): # kill subThread if self.__thread_killer == True: return # if self.__searching or self.__queue_result.qsize() >= block_size: // 永远记住这个 bug (生产者-消费者 问题) if self.__queue_result.qsize() >= block_size: # 如果队列中不小于 block_size 个项 for i in range(block_size): # 取出 block_size 个项 line_block.append(self.__queue_result.get()) # 出队操作 self.__browser_result.addItems(line_block) # 一次性添加 block_size 个条目 line_block.clear() # 清空临时列表 elif self.__queue_result.qsize() >= 0: # 如果队列中小于 block_size 各项 item = self.__queue_result.get() # 出队一项 self.__browser_result.addItem(QListWidgetItem(item)) # 加载到界面 #self.__browser.setCurrentRow(self.__browser.count()-1) # 设置列表中最后一项为当前项,使列表不停滚动 sleep(0.05) # 给界面事件循环腾出时间,避免界面冻结 #self.__pbn_search.setEnabled(True) # 显示出错结果 def show_error_result(self): """打印略过的文件和出错原因,多为 I/O Error""" count = 0 while self.__queue_error.qsize() or self.__searching: # kill subThread if self.__thread_killer == True: return if self.__queue_error.qsize() <= 0: continue self.__browser_error.append(self.__queue_error.get()) count += 1 self.__tabView.setTabText(1, '错误结果(%d)' % count) # 单击检索按钮 def pbn_search_clicked(self): """To search allow the arguments from UI""" # 获取 UI 数据 file_path = self.__ln_file_path.text() file_name = self.__ln_file_name.text() # 检查参数 if file_path == '': QMessageBox(QMessageBox.Warning, '缺少参数!', '请输入搜索路径!', QMessageBox.Ok, self).exec_() return if file_name == '': QMessageBox(QMessageBox.Warning, '缺少参数!', '请输入匹配条件!', QMessageBox.Ok, self).exec_() return # 判断搜索模式 mode = self.__search_mode['fuzzy'] if self.__rbn_reg.isChecked(): mode = self.__search_mode['reg'] elif self.__rbn_fuzzy.isChecked(): mode = self.__search_mode['fuzzy'] elif self.__rbn_precise.isChecked(): mode = self.__search_mode['precise'] # 大小写敏感标记 I = True if self.__rbn_reg_Ino.isChecked(): I = False self.__browser_result.clear() self.__browser_error.clear() self.__tabView.setTabText(0, '匹配结果(0)') self.__tabView.setTabText(1, '错误结果(0)') self.__searching = True # 开启子线程,后台深度遍历 self.__thread_killer = False if self.__rbn_search_file.isChecked(): self.__lab_state.setText('正在搜索......已搜索到 0 个文件') self.__sub_thread_search = Thread(target=self.search_from_filename, args=(file_path, file_name, mode, I)) self.__sub_thread_search.start() else: self.__lab_state.setText('正在搜索......') self.__sub_thread_search = Thread(target=self.search_from_content, args=(file_path, file_name, mode, I)) self.__sub_thread_search.start() # 开启子线程,显示搜索结果 self.__sub_thread_show_result = Thread(target=self.show_search_result) self.__sub_thread_show_result.start() # 开启子线程,显示错误结果 self.__sub_thread_show_error = Thread(target=self.show_error_result) self.__sub_thread_show_error.start() # self.__pbn_search_file.setEnable(False) # self.__pbn_search_content.setEnable(False) # 单击停止按钮 def pbn_stop(self): if not self.__searching: return self.__thread_killer = True while self.__queue_result.qsize(): self.__queue_result.get() while self.__queue_error.qsize(): self.__queue_error.get() self.__lab_state.setText('搜索已停止!') self.__searching = False # 双击搜索结果 def listitem_clicked(self): """Double click to open the file from search result""" file_path = self.__browser_result.currentItem().text().strip() read_tool = self.__ln_open_tool.text() if not exists(file_path): QMessageBox.warning(self, '错误!', '请双击文件名\n%s 不是文件或打不开!' % file_path, QMessageBox.Ok) return if splitext(file_path)[1] in ['.jpg', '.png', '.jpeg', '.gif']: file_path = r'%s'.replace(' ', r'\ ') % file_path system('%s' % file_path) else: system('"%s" %s' % (read_tool, file_path))
class FirstTab(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): # Groupbox call grid = QGridLayout() grid.addWidget(self.createGB0(), 0, 0) grid.addWidget(self.createGB1(), 0, 1) self.setLayout(grid) # Groupbox: 주문현황 def createGB0(self): gbox = QGroupBox('주문현황') hbox = QHBoxLayout() vbox = QVBoxLayout() # widget 정의 self.orderlist = [] self.listwidget = QListWidget() self.listwidget.addItems(self.orderlist) vbox.addWidget(self.listwidget) btn_totcancel = QPushButton('전체취소', self) btn_printbill = QPushButton('영수증출력', self) hbox.addWidget(btn_printbill) hbox.addWidget(btn_totcancel) vbox.addLayout(hbox) gbox.setLayout(vbox) # Signal btn_totcancel.clicked.connect(self.totalCancel) return gbox # Groupbox: 메뉴선택 def createGB1(self): gbox = QGroupBox('메뉴선택') vbox = QVBoxLayout() # widget list 정의 btns_menu = [] # widget 정의 및 추가 for문 for i in range(len(menu_list)): btns_menu.append(QPushButton(menu_list[i].name + '\n' + str(menu_list[i].cost) + '원', self)) vbox.addWidget(btns_menu[i]) # Signal btns_menu[0].clicked.connect(lambda: self.menuClicked(0)) btns_menu[1].clicked.connect(lambda: self.menuClicked(1)) btns_menu[2].clicked.connect(lambda: self.menuClicked(2)) btns_menu[3].clicked.connect(lambda: self.menuClicked(3)) gbox.setLayout(vbox) return gbox # Slot # 주문현황 list에 주문한 메뉴만 있도록 @pyqtSlot() def orderChanged(self): # 전체 수량이 0일 경우 if total.qt == 0: self.orderlist = [] self.listwidget.clear() else: for i in range(len(menu_list)): if menu_list[i].qt != 0: if menu_list[i].name in self.orderlist: pass else: self.orderlist.append(menu_list[i].name) self.listwidget.addItem(self.orderlist[-1]) # 수량 변경/취소 @pyqtSlot(int) def menuClicked(self, i): menu_list[i].menu_qt(1) self.orderChanged() # 전체취소 @pyqtSlot() def totalCancel(self): americano.tot_cancel() self.orderChanged()
class ListEdit(QWidget): """A widget to edit a list of items (e.g. a list of directories).""" # emitted when anything changed in the listbox. changed = pyqtSignal() def __init__(self, *args, **kwargs): QWidget.__init__(self, *args, **kwargs) layout = QGridLayout(self) self.setLayout(layout) self.addButton = QPushButton(icons.get('list-add'), '') self.editButton = QPushButton(icons.get('document-edit'), '') self.removeButton = QPushButton(icons.get('list-remove'), '') self.listBox = QListWidget() layout.setContentsMargins(1, 1, 1, 1) layout.setSpacing(0) layout.addWidget(self.listBox, 0, 0, 8, 1) layout.addWidget(self.addButton, 0, 1) layout.addWidget(self.editButton, 1, 1) layout.addWidget(self.removeButton, 2, 1) @self.addButton.clicked.connect def addClicked(): item = self.createItem() if self.openEditor(item): self.addItem(item) @self.editButton.clicked.connect def editClicked(): item = self.listBox.currentItem() item and self.editItem(item) @self.removeButton.clicked.connect def removeClicked(): item = self.listBox.currentItem() if item: self.removeItem(item) @self.listBox.itemDoubleClicked.connect def itemDoubleClicked(item): item and self.editItem(item) self.listBox.model().layoutChanged.connect(self.changed) def updateSelection(): selected = bool(self.listBox.currentItem()) self.editButton.setEnabled(selected) self.removeButton.setEnabled(selected) self.changed.connect(updateSelection) self.listBox.itemSelectionChanged.connect(updateSelection) updateSelection() app.translateUI(self) def translateUI(self): self.addButton.setText(_("&Add...")) self.editButton.setText(_("&Edit...")) self.removeButton.setText(_("&Remove")) def createItem(self): return QListWidgetItem() def addItem(self, item): self.listBox.addItem(item) self.itemChanged(item) self.changed.emit() def removeItem(self, item): self.listBox.takeItem(self.listBox.row(item)) self.changed.emit() def editItem(self, item): if self.openEditor(item): self.itemChanged(item) self.changed.emit() def setCurrentItem(self, item): self.listBox.setCurrentItem(item) def setCurrentRow(self, row): self.listBox.setCurrentRow(row) def openEditor(self, item): """Opens an editor (dialog) for the item. Returns True if the dialog was accepted and the item edited. Returns False if the dialog was cancelled (the item must be left unedited). """ pass def itemChanged(self, item): """Called after an item has been added or edited. Re-implement to do something at this moment if needed, e.g. alter the text or display of other items. """ pass def setValue(self, strings): """Sets the listbox to a list of strings.""" self.listBox.clear() self.listBox.addItems(strings) self.changed.emit() def value(self): """Returns the list of paths in the listbox.""" return [ self.listBox.item(i).text() for i in range(self.listBox.count()) ] def setItems(self, items): """Sets the listbox to a list of items.""" self.listBox.clear() for item in items: self.listBox.addItem(item) self.itemChanged(item) self.changed.emit() def items(self): """Returns the list of items in the listbox.""" return [self.listBox.item(i) for i in range(self.listBox.count())] def clear(self): """Clears the listbox.""" self.listBox.clear() self.changed.emit()
class UiMainWindow(object): def __init__(self): super(UiMainWindow, self).__init__() self.setupUi(self) self.numb1 = 0 def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") desktop = QtWidgets.QApplication.desktop() x = (desktop.width() - 801) // 2 y = (desktop.height() - 612) // 2 MainWindow.move(x, y) MainWindow.resize(801, 612) MainWindow.setFixedSize(801, 612) MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) MainWindow.setStyleSheet( 'QListWidget{border:1px solid gray; color:black; }' 'QListWidget::Item{padding-top:-2px; padding-bottom:-1px;}' "QListWidget::Item:hover{background:skyblue;padding-top:0px; padding-bottom:0px; }" #"QListWidget::item:selected{background:lightpink; color:red; }" #"QListWidget::item:selected:!active{active{border-width:0px;background:lightgreen; }" ) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.frame_2 = QtWidgets.QFrame(self.centralwidget) self.frame_2.setGeometry(QtCore.QRect(0, 20, 801, 591)) self.frame_2.setFrameShape(QtWidgets.QFrame.NoFrame) self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_2.setLineWidth(1) self.frame_2.setObjectName("frame_2") self.tabWidget = QtWidgets.QTabWidget(self.frame_2) self.tabWidget.setGeometry(QtCore.QRect(0, 0, 801, 338)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(False) font.setWeight(0) self.tabWidget.setFont(font) self.tabWidget.setContextMenuPolicy(QtCore.Qt.NoContextMenu) self.tabWidget.setToolTipDuration(0) self.tabWidget.setIconSize(QtCore.QSize(20, 20)) self.tabWidget.setObjectName("tabWidget") # ##设置 通用listwidget # self.liwidget = QListWidget() self.tab_1 = QtWidgets.QWidget() self.tab_1.setMouseTracking(True) self.tab_1.setTabletTracking(True) self.tab_1.setObjectName("tab_1") self.icon1 = QtGui.QIcon() self.icon1.addPixmap(QtGui.QPixmap(cwd + "/ico/fpg.ico"), QtGui.QIcon.Normal, QtGui.QIcon.On) self.icon2 = QtGui.QIcon() self.icon2.addPixmap(QtGui.QPixmap(cwd + "/ico/qpg.ico"), QtGui.QIcon.Normal, QtGui.QIcon.On) self.widget = QtWidgets.QWidget(self.tab_1) self.widget.setGeometry(QtCore.QRect(0, 0, 801, 309)) self.widget.setObjectName("widget_1") self.pzbt = QtWidgets.QPushButton(self.widget) self.pzbt.setGeometry(QtCore.QRect(710, 20, 75, 23)) self.pzbt.setObjectName("pzbt_1") self.uploadbt_1 = QtWidgets.QPushButton(self.widget) self.uploadbt_1.setGeometry(QtCore.QRect(710, 80, 75, 23)) self.uploadbt_1.setObjectName("uploadbt_1") self.label_1 = QtWidgets.QLabel(self.widget) self.label_1.setGeometry(QtCore.QRect(710, 270, 60, 23)) self.label_1.setText("已下载:") self.label_11 = QtWidgets.QLabel(self.widget) self.label_11.setGeometry(QtCore.QRect(750, 270, 40, 23)) self.listWidget_1 = QListWidget(self.widget) self.listWidget_1.setGeometry(QtCore.QRect(0, 0, 691, 308)) self.listWidget_1.setObjectName("listWidget_1") ## 数据模型1 self.listWidget_1.addItems([ r'D:\workspace\project\pyqt\biguo2\wantiku\集群.xlsx', r'wantiku\2013年10月《中国法制史》真题.xlsx', r"wantiku\1.xlsx" ]) self.tabWidget.addTab(self.tab_1, "0") self.tab_2 = QtWidgets.QWidget() self.tab_2.setObjectName("tab_2") self.widget_2 = QtWidgets.QWidget(self.tab_2) self.widget_2.setGeometry(QtCore.QRect(0, 0, 801, 309)) self.widget_2.setObjectName("widget_2") self.pzbt_2 = QtWidgets.QPushButton(self.widget_2) self.pzbt_2.setGeometry(QtCore.QRect(710, 20, 75, 23)) self.pzbt_2.setObjectName("pzbt_2") self.uploadbt_2 = QtWidgets.QPushButton(self.widget_2) self.uploadbt_2.setGeometry(QtCore.QRect(710, 80, 75, 23)) self.uploadbt_2.setObjectName("uploadbt_2") self.listWidget_2 = QListWidget(self.widget_2) self.listWidget_2.setGeometry(QtCore.QRect(0, 0, 691, 308)) self.listWidget_2.setObjectName("listWidget_2") self.label_2 = QtWidgets.QLabel(self.widget_2) self.label_2.setGeometry(QtCore.QRect(710, 270, 60, 23)) self.label_2.setText("已下载:") self.label_22 = QtWidgets.QLabel(self.widget_2) self.label_22.setGeometry(QtCore.QRect(750, 270, 40, 23)) self.label_22.setText("-----") self.tabWidget.addTab(self.tab_2, "1") self.tab_3 = QtWidgets.QWidget() self.tab_3.setObjectName("tab_3") self.widget_3 = QtWidgets.QWidget(self.tab_3) self.widget_3.setGeometry(QtCore.QRect(0, 0, 801, 309)) self.widget_3.setObjectName("widget_3") self.pzbt_3 = QtWidgets.QPushButton(self.widget_3) self.pzbt_3.setGeometry(QtCore.QRect(710, 20, 75, 23)) self.pzbt_3.setObjectName("pzbt_3") self.uploadbt_3 = QtWidgets.QPushButton(self.widget_3) self.uploadbt_3.setGeometry(QtCore.QRect(710, 80, 75, 23)) self.uploadbt_3.setObjectName("uploadbt_3") self.listWidget_3 = QListWidget(self.widget_3) self.listWidget_3.setGeometry(QtCore.QRect(0, 0, 691, 308)) self.listWidget_3.setObjectName("listWidget_3") self.label_3 = QtWidgets.QLabel(self.widget_3) self.label_3.setGeometry(QtCore.QRect(710, 270, 60, 23)) self.label_3.setText("已下载:") self.label_33 = QtWidgets.QLabel(self.widget_3) self.label_33.setGeometry(QtCore.QRect(750, 270, 40, 23)) self.label_33.setText("-----") self.tabWidget.addTab(self.tab_3, "") self.tab_4 = QtWidgets.QWidget() self.tab_4.setObjectName("tab_4") self.widget_4 = QtWidgets.QWidget(self.tab_4) self.widget_4.setGeometry(QtCore.QRect(0, 0, 801, 309)) self.widget_4.setObjectName("widget_4") self.pzbt_4 = QtWidgets.QPushButton(self.widget_4) self.pzbt_4.setGeometry(QtCore.QRect(710, 20, 75, 23)) self.pzbt_4.setObjectName("pzbt_4") self.uploadbt_4 = QtWidgets.QPushButton(self.widget_4) self.uploadbt_4.setGeometry(QtCore.QRect(710, 80, 75, 23)) self.uploadbt_4.setObjectName("uploadbt_4") self.listWidget_4 = QListWidget(self.widget_4) self.listWidget_4.setGeometry(QtCore.QRect(0, 0, 691, 308)) self.listWidget_4.setObjectName("listWidget_4") self.label_4 = QtWidgets.QLabel(self.widget_4) self.label_4.setGeometry(QtCore.QRect(710, 270, 60, 23)) self.label_4.setText("已下载:") self.label_44 = QtWidgets.QLabel(self.widget_4) self.label_44.setGeometry(QtCore.QRect(750, 270, 40, 23)) self.label_44.setText("-----") self.tabWidget.addTab(self.tab_4, "") self.tab_5 = QtWidgets.QWidget() self.tab_5.setObjectName("tab_5") self.widget_5 = QtWidgets.QWidget(self.tab_5) self.widget_5.setGeometry(QtCore.QRect(0, 0, 801, 309)) self.widget_5.setObjectName("widget_5") self.pzbt_5 = QtWidgets.QPushButton(self.widget_5) self.pzbt_5.setGeometry(QtCore.QRect(710, 20, 75, 23)) self.pzbt_5.setObjectName("pzbt_5") self.uploadbt_5 = QtWidgets.QPushButton(self.widget_5) self.uploadbt_5.setGeometry(QtCore.QRect(710, 80, 75, 23)) self.uploadbt_5.setObjectName("uploadbt_5") self.listWidget_5 = QListWidget(self.widget_5) self.listWidget_5.setGeometry(QtCore.QRect(0, 0, 691, 308)) self.listWidget_5.setObjectName("listWidget_5") self.label_5 = QtWidgets.QLabel(self.widget_5) self.label_5.setGeometry(QtCore.QRect(710, 270, 60, 23)) self.label_5.setText("已下载:") self.label_55 = QtWidgets.QLabel(self.widget_5) self.label_55.setGeometry(QtCore.QRect(750, 270, 40, 23)) self.label_55.setText("-----") self.tabWidget.addTab(self.tab_5, "") self.tab_6 = QtWidgets.QWidget() self.tab_6.setObjectName("tab_6") self.widget_6 = QtWidgets.QWidget(self.tab_6) self.widget_6.setGeometry(QtCore.QRect(0, 0, 801, 309)) self.widget_6.setObjectName("widget_6") self.pzbt_6 = QtWidgets.QPushButton(self.widget_6) self.pzbt_6.setGeometry(QtCore.QRect(710, 20, 75, 23)) self.pzbt_6.setObjectName("pzbt_6") self.uploadbt_6 = QtWidgets.QPushButton(self.widget_6) self.uploadbt_6.setGeometry(QtCore.QRect(710, 80, 75, 23)) self.uploadbt_6.setObjectName("uploadbt_6") self.listWidget_6 = QListWidget(self.widget_6) self.listWidget_6.setGeometry(QtCore.QRect(0, 0, 691, 308)) self.listWidget_6.setObjectName("listWidget_6") self.label_6 = QtWidgets.QLabel(self.widget_6) self.label_6.setGeometry(QtCore.QRect(710, 270, 60, 23)) self.label_6.setText("已下载:") self.label_66 = QtWidgets.QLabel(self.widget_6) self.label_66.setGeometry(QtCore.QRect(750, 270, 40, 23)) self.label_66.setText("-----") self.tabWidget.addTab(self.tab_6, "") self.tab_7 = QtWidgets.QWidget() self.tab_7.setObjectName("tab_7") self.widget_7 = QtWidgets.QWidget(self.tab_7) self.widget_7.setGeometry(QtCore.QRect(0, 0, 801, 309)) self.widget_7.setObjectName("widget_7") self.pzbt_7 = QtWidgets.QPushButton(self.widget_7) self.pzbt_7.setGeometry(QtCore.QRect(710, 20, 75, 23)) self.pzbt_7.setObjectName("pzbt_7") self.uploadbt_7 = QtWidgets.QPushButton(self.widget_7) self.uploadbt_7.setGeometry(QtCore.QRect(710, 80, 75, 23)) self.uploadbt_7.setObjectName("uploadbt_7") self.listWidget_7 = QListWidget(self.widget_7) self.listWidget_7.setGeometry(QtCore.QRect(0, 0, 691, 308)) self.listWidget_7.setObjectName("listWidget_7") self.label_7 = QtWidgets.QLabel(self.widget_7) self.label_7.setGeometry(QtCore.QRect(710, 270, 60, 23)) self.label_7.setText("已下载:") self.label_77 = QtWidgets.QLabel(self.widget_7) self.label_77.setGeometry(QtCore.QRect(750, 270, 40, 23)) self.label_77.setText("-----") self.tabWidget.addTab(self.tab_7, "") self.frame = QtWidgets.QFrame(self.frame_2) self.frame.setGeometry(QtCore.QRect(0, 330, 801, 71)) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName("frame") self.checkBox1 = QtWidgets.QCheckBox(self.frame) self.checkBox1.setGeometry(QtCore.QRect(20, 10, 71, 16)) self.checkBox1.setObjectName("checkBox1") self.checkBox3 = QtWidgets.QCheckBox(self.frame) self.checkBox3.setGeometry(QtCore.QRect(170, 10, 71, 16)) self.checkBox3.setObjectName("checkBox3") self.checkBox5 = QtWidgets.QCheckBox(self.frame) self.checkBox5.setGeometry(QtCore.QRect(340, 10, 71, 16)) self.checkBox5.setObjectName("checkBox5") self.checkBox6 = QtWidgets.QCheckBox(self.frame) self.checkBox6.setGeometry(QtCore.QRect(410, 10, 71, 16)) self.checkBox6.setObjectName("checkBox6") self.checkBox4 = QtWidgets.QCheckBox(self.frame) self.checkBox4.setGeometry(QtCore.QRect(250, 10, 71, 16)) self.checkBox4.setObjectName("checkBox4") self.checkBox7 = QtWidgets.QCheckBox(self.frame) self.checkBox7.setGeometry(QtCore.QRect(500, 10, 71, 16)) self.checkBox7.setObjectName("checkBox7") self.checkBox2 = QtWidgets.QCheckBox(self.frame) self.checkBox2.setGeometry(QtCore.QRect(90, 10, 71, 16)) self.checkBox2.setObjectName("checkBox2") self.stbt = QtWidgets.QPushButton(self.frame) self.stbt.setGeometry(QtCore.QRect(710, 40, 75, 23)) self.stbt.setAutoFillBackground(False) self.stbt.setStyleSheet("") self.stbt.setCheckable(True) self.stbt.setAutoDefault(False) self.stbt.setDefault(False) self.stbt.setFlat(False) self.stbt.setObjectName("stbt") self.spsetbt = QtWidgets.QPushButton(self.frame) self.spsetbt.setGeometry(QtCore.QRect(710, 10, 75, 23)) self.spsetbt.setObjectName("spsetbt") self.groupBox = QtWidgets.QGroupBox(self.frame_2) self.groupBox.setGeometry(QtCore.QRect(0, 400, 801, 191)) self.groupBox.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) self.groupBox.setToolTipDuration(-1) self.groupBox.setFlat(False) self.groupBox.setCheckable(False) self.groupBox.setObjectName("groupBox") self.printtext = QtWidgets.QTextEdit(self.groupBox) self.printtext.setGeometry(QtCore.QRect(0, 10, 801, 181)) self.printtext.setTextInteractionFlags( QtCore.Qt.TextSelectableByKeyboard | QtCore.Qt.TextSelectableByMouse) self.printtext.setObjectName("printtext") self.userlabel = QtWidgets.QLabel(self.centralwidget) self.userlabel.setGeometry(QtCore.QRect(700, 0, 91, 20)) self.userlabel.setScaledContents(False) self.userlabel.setWordWrap(False) self.userlabel.setObjectName("userlabel") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) self.spsetbt.clicked.connect(MainWindow.set_spider) self.stbt.toggled['bool'].connect(MainWindow.spider_handle) self.uploadbt_1.clicked.connect(MainWindow.upload1) self.uploadbt_2.clicked.connect(MainWindow.upload1) self.uploadbt_3.clicked.connect(MainWindow.upload1) self.uploadbt_4.clicked.connect(MainWindow.upload1) self.uploadbt_5.clicked.connect(MainWindow.upload1) self.uploadbt_6.clicked.connect(MainWindow.upload1) self.uploadbt_7.clicked.connect(MainWindow.upload1) self.checkBox1.toggled.connect(MainWindow.cbedit1) self.checkBox2.toggled.connect(MainWindow.cbedit1) self.checkBox3.toggled.connect(MainWindow.cbedit1) self.checkBox4.toggled.connect(MainWindow.cbedit1) self.checkBox5.toggled.connect(MainWindow.cbedit1) self.checkBox6.toggled.connect(MainWindow.cbedit1) self.checkBox7.toggled.connect(MainWindow.cbedit1) #设置右键菜单 self.listWidget_1.setContextMenuPolicy(3) #self.listWidget_1.itemClicked.connect(self.rk_menu) self.listWidget_1.itemDoubleClicked.connect(MainWindow.file_open) self.listWidget_1.customContextMenuRequested[QtCore.QPoint].connect( self.rk_menu) self.listWidget_2.setContextMenuPolicy(3) self.listWidget_2.customContextMenuRequested[QtCore.QPoint].connect( self.rk_menu) self.listWidget_2.doubleClicked.connect(MainWindow.file_open) self.listWidget_3.setContextMenuPolicy(3) self.listWidget_3.customContextMenuRequested[QtCore.QPoint].connect( self.rk_menu) self.listWidget_3.doubleClicked.connect(MainWindow.file_open) self.listWidget_4.setContextMenuPolicy(3) self.listWidget_4.customContextMenuRequested[QtCore.QPoint].connect( self.rk_menu) self.listWidget_4.doubleClicked.connect(MainWindow.file_open) self.listWidget_5.setContextMenuPolicy(3) self.listWidget_5.customContextMenuRequested[QtCore.QPoint].connect( self.rk_menu) self.listWidget_5.doubleClicked.connect(MainWindow.file_open) self.listWidget_6.setContextMenuPolicy(3) self.listWidget_6.customContextMenuRequested[QtCore.QPoint].connect( self.rk_menu) self.listWidget_6.doubleClicked.connect(MainWindow.file_open) self.listWidget_7.setContextMenuPolicy(3) self.listWidget_7.customContextMenuRequested[QtCore.QPoint].connect( self.rk_menu) self.listWidget_7.doubleClicked.connect(MainWindow.file_open) # 列表设置字体 self.listWidget_1.setFont(font) self.listWidget_2.setFont(font) self.listWidget_3.setFont(font) self.listWidget_4.setFont(font) self.listWidget_5.setFont(font) self.listWidget_6.setFont(font) self.listWidget_7.setFont(font) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "笔果数据管理")) MainWindow.setWindowIcon(QtGui.QIcon('./ico/cm02.ico')) # self.tabWidget.setTabIcon(0,self.icon1) # self.tabWidget.setTabIcon(1, self.icon1) # self.tabWidget.setTabIcon(2, self.icon1) # self.tabWidget.setTabIcon(3, self.icon1) # self.tabWidget.setTabIcon(4, self.icon1) # self.tabWidget.setTabIcon(5, self.icon1) # self.tabWidget.setTabIcon(6, self.icon1) self.pzbt.setText(_translate("MainWindow", "配置修改")) self.uploadbt_1.setText(_translate("MainWindow", "开始上传")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_1), _translate("MainWindow", "万题库")) self.pzbt_2.setText(_translate("MainWindow", "配置修改")) self.uploadbt_2.setText(_translate("MainWindow", "开始上传")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "自考真题库")) self.pzbt_3.setText(_translate("MainWindow", "配置修改")) self.uploadbt_3.setText(_translate("MainWindow", "开始上传")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "自考友")) self.pzbt_4.setText(_translate("MainWindow", "配置修改")) self.uploadbt_4.setText(_translate("MainWindow", "开始上传")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), _translate("MainWindow", "答题易")) self.pzbt_5.setText(_translate("MainWindow", "配置修改")) self.uploadbt_5.setText(_translate("MainWindow", "开始上传")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), _translate("MainWindow", "自考5网站")) self.pzbt_6.setText(_translate("MainWindow", "配置修改")) self.uploadbt_6.setText(_translate("MainWindow", "开始上传")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_6), _translate("MainWindow", "百度文库")) self.pzbt_7.setText(_translate("MainWindow", "配置修改")) self.uploadbt_7.setText(_translate("MainWindow", "开始上传")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_7), _translate("MainWindow", "自考365app")) self.checkBox1.setText(_translate("MainWindow", "万题库")) self.checkBox3.setText(_translate("MainWindow", "自考友")) self.checkBox5.setText(_translate("MainWindow", "自考5")) self.checkBox6.setText(_translate("MainWindow", "百度文库")) self.checkBox4.setText(_translate("MainWindow", "答题易")) self.checkBox7.setText(_translate("MainWindow", "365app")) self.checkBox2.setText(_translate("MainWindow", "真题库")) self.stbt.setText(_translate("MainWindow", "开始")) self.spsetbt.setText(_translate("MainWindow", "爬虫设置")) self.groupBox.setTitle(_translate("MainWindow", "调试信息")) self.userlabel.setText(_translate("MainWindow", "User")) def set_spider(self): pass def file_open(self, e): print("doublec") # excelapp = client.Dispatch("Excel.Application") # excelapp.Visible = -1 # excelapp.Workbooks.Open("D:\workspace\project\pyqt\\biguo2\wantiku\\1.xlsx") # QtCore.QModelIndex # self.sender().setStyleSheet("QListWidget::item:selected{background:lightgray; color:green; }") try: #self.sender().item(e.row()).setForeground(QtGui.QColor('green')) e.setForeground(QtGui.QColor('green')) except Exception as re: print(re) def rk_menu(self, e): # 弹出右键菜单 try: if not self.listWidget_1.itemAt(e.x(), e.y()): return # print('弹出菜单',e.x(),e.y(),self.sender()) a = self.sender() popMenu = QtWidgets.QMenu(self.listWidget_1) popMenu.addAction(Qt.QAction('删除', self)) qp = Qt.QPoint(Qt.QCursor.pos().x() + 1, Qt.QCursor.pos().y()) try: # popMenu.triggered.connect(lambda: self.rm(a,e.x(),e.y())) popMenu.triggered.connect(partial(self.rm, a, e)) # 绑定删除按钮的方法,用 partial 函数传递额外参数,还可以用匿名函数,但是匿名函数不带默认参数 except Exception as e: print(e) popMenu.exec_(qp) except Exception as e: print(e) def rm(self, liw, pos, e): # 右键菜单删除功能 # print(liw, pos, e) try: if e.text() == "删除": item = liw.itemAt(pos.x(), pos.y()) print("删除第%d行:%s" % (liw.row(item) + 1, item.text())) liw.removeItemWidget(liw.takeItem(liw.row(item))) self.flushnum() #liw.updateEditorData() #print(e.text(),e.senderSignalIndex(),self.sender()) #QtWidgets.QMenu.at #QtWidgets.QAction. except Exception as e: print(e) def flushnum(self): # 实时显示列表中的试卷数目。*** self.label_11.setText(str(len(self.listWidget_1))) self.label_22.setText(str(len(self.listWidget_2))) self.label_33.setText(str(len(self.listWidget_3))) self.label_44.setText(str(len(self.listWidget_4))) self.label_55.setText(str(len(self.listWidget_5))) self.label_66.setText(str(len(self.listWidget_6))) self.label_77.setText(str(len(self.listWidget_7)))
class FindDialog(QDialog): alphabetical = [dict(type="alphabetical", allowPseudoUnicode=True)] def __init__(self, currentGlyph, parent=None): super().__init__(parent) self.setWindowModality(Qt.WindowModal) self.setWindowTitle(self.tr("Find…")) self.font = currentGlyph.font self._sortedGlyphNames = self.font.unicodeData.sortGlyphNames(self.font.keys(), self.alphabetical) layout = QGridLayout(self) self.glyphLabel = QLabel(self.tr("Glyph:"), self) self.glyphEdit = QLineEdit(self) self.glyphEdit.textChanged.connect(self.updateGlyphList) self.glyphEdit.event = self.lineEvent self.glyphEdit.keyPressEvent = self.lineKeyPressEvent self.beginsWithBox = QRadioButton(self.tr("Begins with"), self) self.containsBox = QRadioButton(self.tr("Contains"), self) self.beginsWithBox.setChecked(True) self.beginsWithBox.toggled.connect(self.updateGlyphList) self.glyphList = QListWidget(self) self.glyphList.itemDoubleClicked.connect(self.accept) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) l = 0 layout.addWidget(self.glyphLabel, l, 0, 1, 2) layout.addWidget(self.glyphEdit, l, 2, 1, 4) l += 1 layout.addWidget(self.beginsWithBox, l, 0, 1, 3) layout.addWidget(self.containsBox, l, 3, 1, 3) l += 1 layout.addWidget(self.glyphList, l, 0, 1, 6) l += 1 layout.addWidget(buttonBox, l, 0, 1, 6) self.setLayout(layout) self.updateGlyphList() def lineEvent(self, event): if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab: if self.beginsWithBox.isChecked(): self.containsBox.toggle() else: self.beginsWithBox.toggle() return True else: return QLineEdit.event(self.glyphEdit, event) def lineKeyPressEvent(self, event): key = event.key() if key == Qt.Key_Up or key == Qt.Key_Down: self.glyphList.keyPressEvent(event) else: QLineEdit.keyPressEvent(self.glyphEdit, event) def updateGlyphList(self): beginsWith = self.beginsWithBox.isChecked() self.glyphList.clear() if not self.glyphEdit.isModified(): self.glyphList.addItems(self._sortedGlyphNames) else: text = self.glyphEdit.text() if beginsWith: glyphs = [glyphName for glyphName in self._sortedGlyphNames if glyphName and glyphName.startswith(text)] else: glyphs = [glyphName for glyphName in self._sortedGlyphNames if glyphName and text in glyphName] self.glyphList.addItems(glyphs) self.glyphList.setCurrentRow(0) @classmethod def getNewGlyph(cls, parent, currentGlyph): dialog = cls(currentGlyph, parent) result = dialog.exec_() currentItem = dialog.glyphList.currentItem() newGlyph = None if currentItem is not None: newGlyphName = currentItem.text() if newGlyphName in dialog.font: newGlyph = dialog.font[newGlyphName] return (newGlyph, result)
class VariableSettingWindowDemo(QDialog): def __init__(self, data_list): super(VariableSettingWindowDemo, self).__init__() self.initUI(data_list) def initUI(self, data_list): self.resize(800, 800) self.setWindowTitle('变量设置') self.signal = MySignal() icon = QIcon() icon.addPixmap(QPixmap('../image/设置.png')) self.setWindowIcon(icon) self.label1 = QLabel('变量') self.label2 = QLabel('自变量') self.label3 = QLabel('因变量') self.list_widget1 = QListWidget() self.list_widget2 = QListWidget() self.list_widget3 = QListWidget() self.list_widget1.setSelectionMode(QAbstractItemView.ExtendedSelection) self.list_widget2.setSelectionMode(QAbstractItemView.ExtendedSelection) self.list_widget3.setSelectionMode(QAbstractItemView.ExtendedSelection) self.list_widget1.addItems(data_list) self.button12 = QPushButton('-->') self.button21 = QPushButton('<--') self.button13 = QPushButton('-->') self.button31 = QPushButton('<--') self.button1 = QPushButton('确认') self.button2 = QPushButton('取消') vlayout1 = QVBoxLayout() vlayout1.addWidget(self.button12) vlayout1.addWidget(self.button21) hlayout1 = QHBoxLayout() hlayout1.addItem(vlayout1) vlayout = QVBoxLayout() # vlayout.addWidget(QLabel('')) vlayout.addWidget(self.label2) vlayout.addWidget(self.list_widget2) vlayout.setSpacing(10) hlayout1.addItem(vlayout) vlayout2 = QVBoxLayout() vlayout2.addWidget(self.button13) vlayout2.addWidget(self.button31) hlayout2 = QHBoxLayout() hlayout2.addItem(vlayout2) vlayout = QVBoxLayout() # vlayout.addWidget(QLabel('')) vlayout.addWidget(self.label3) vlayout.addWidget(self.list_widget3) vlayout.setSpacing(10) hlayout2.addItem(vlayout) gridlayout = QGridLayout() hlayout = QHBoxLayout() # hlayout.addWidget(self.button1) # hlayout.addWidget(self.button2) hlayout.setSpacing(20) vlayout = QVBoxLayout() vlayout.addItem(hlayout) vlayout.addWidget(self.label1) vlayout.addWidget(self.list_widget1) vlayout.setSpacing(10) gridlayout.addItem(vlayout, 1, 0, 2, 1) hlayout1.setSpacing(10) hlayout2.setSpacing(10) gridlayout.addItem(hlayout1, 1, 1, 1, 1) gridlayout.addItem(hlayout2, 2, 1, 1, 1) hlayout = QHBoxLayout() hlayout.addWidget(self.button1) hlayout.addWidget(self.button2) hlayout.setSpacing(10) gridlayout.addItem(hlayout, 3, 0, 1, 1) self.setLayout(gridlayout) #绑定信号 self.button12.clicked.connect( lambda: self.onClickButton(self.list_widget1, self.list_widget2)) self.button21.clicked.connect( lambda: self.onClickButton(self.list_widget2, self.list_widget1)) self.button13.clicked.connect( lambda: self.onClickButton(self.list_widget1, self.list_widget3)) self.button31.clicked.connect( lambda: self.onClickButton(self.list_widget3, self.list_widget1)) self.button1.clicked.connect(self.sendSignal) self.button2.clicked.connect(self.close) def onClickButton(self, sender, reciever): try: item_list = sender.selectedItems() for item in item_list: reciever.addItem(item.text()) sender.takeItem(sender.row(item)) except Exception as e: print(e) def sendSignal(self): count1 = self.list_widget2.count() count2 = self.list_widget3.count() independ_var = [ self.list_widget2.item(i).text() for i in range(count1) ] depend_var = [self.list_widget3.item(i).text() for i in range(count2)] var_list = [independ_var, depend_var] self.signal.send(var_list) self.close()
class CityListDlg(QDialog): citieslist_signal = pyqtSignal([list]) def __init__(self, citylist, accurate_url, appid, parent=None): super(CityListDlg, self).__init__(parent) self.citylist = citylist self.accurate_url = accurate_url self.appid = appid self.listWidget = QListWidget() self.listWidget.addItems(self.citylist) buttonLayout = QVBoxLayout() self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.rejected.connect(self.reject) self.buttonBox.accepted.connect(self.accept) layoutT = QVBoxLayout() layout = QHBoxLayout() layout.addWidget(self.listWidget) layout.addLayout(buttonLayout) for text, slot in ((self.tr("&Add..."), self.add), (self.tr("&Remove..."), self.remove), (self.tr("&Up"), self.up), (self.tr("&Down"), self.down), (self.tr("De&fault"), self.default), (self.tr("&Sort"), self.listWidget.sortItems)): button = QPushButton(text) buttonLayout.addWidget(button) button.clicked.connect(slot) buttonLayout.addWidget(self.buttonBox) self.status = QLabel() layoutT.addLayout(layout) layoutT.addWidget(self.status) self.setLayout(layoutT) self.checklength() def add(self): self.status.setText('') lista = [] newitem = '' self.citytoadd = '' self.countrytoadd = '' self._idtoadd = '' dialog = searchcity.SearchCity(self.accurate_url, self.appid, self) dialog.id_signal.connect(self.addcity) dialog.city_signal.connect(self.addcity) dialog.country_signal.connect(self.addcity) if dialog.exec_() == 1: newitem = (self.citytoadd + '_' + self.countrytoadd + '_' + self._idtoadd) for row in range(self.listWidget.count()): lista.append(self.listWidget.item(row).text()) if newitem in lista: self.status.setText(QCoreApplication.translate('Status bar message', 'The city already exists in the list', 'Cities list dialogue')) return else: self.listWidget.addItem(newitem) self.checklength() def addcity(self, what): self.status.setText('') if what[0] == 'ID': self._idtoadd = what[1] elif what[0] == 'City': self.citytoadd = what[1] elif what[0] == 'Country': self.countrytoadd = what[1] def remove(self): self.status.setText('') if self.listWidget.count() == 0: self.status.setText(self.tr('The list is empty')) return row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is None: return message = self.tr('The city "{0}" has been removed').format( self.listWidget.item(row).text()) item = self.listWidget.takeItem(row) del item self.status.setText(message) def up(self): self.status.setText('') row = self.listWidget.currentRow() if row >= 1: item = self.listWidget.takeItem(row) self.listWidget.insertItem(row - 1, item) self.listWidget.setCurrentItem(item) def down(self): self.status.setText('') row = self.listWidget.currentRow() if row < self.listWidget.count() - 1: item = self.listWidget.takeItem(row) self.listWidget.insertItem(row + 1, item) self.listWidget.setCurrentItem(item) def default(self): self.status.setText('') row = self.listWidget.currentRow() if row >= 1: item = self.listWidget.takeItem(row) self.listWidget.insertItem(0, item) self.listWidget.setCurrentItem(item) def checklength(self): listtosend = [] for row in range(self.listWidget.count()): listtosend.append(self.listWidget.item(row).text()) if len(listtosend) == 0: return self.listWidget.setMinimumWidth(self.listWidget.sizeHintForColumn(0)) def accept(self): listtosend = [] for row in range(self.listWidget.count()): listtosend.append(self.listWidget.item(row).text()) self.citieslist_signal[list].emit(listtosend) QDialog.accept(self)
class SubwindowBrowserSources(QWidget): """Show connections settings sub window.""" current_tab = -1 def createWindow(self, mainWindow, tab=''): """Create window.""" try: parent = None super().__init__(parent) # self.setWindowFlags(Qt.WindowStaysOnTopHint) self.setWindowIcon( QIcon(scctool.settings.getResFile('browser.png'))) self.setWindowModality(Qt.ApplicationModal) self.mainWindow = mainWindow self.passEvent = False self.controller = mainWindow.controller self.__dataChanged = False self.createButtonGroup() self.createTabs(tab) mainLayout = QVBoxLayout() mainLayout.addWidget(self.tabs) mainLayout.addLayout(self.buttonGroup) self.setLayout(mainLayout) self.resize( QSize(int(mainWindow.size().width() * 0.8), self.sizeHint().height())) relativeChange = QPoint(int(mainWindow.size().width() / 2), int(mainWindow.size().height() / 3)) -\ QPoint(int(self.size().width() / 2), int(self.size().height() / 3)) self.move(mainWindow.pos() + relativeChange) self.setWindowTitle(_("Browser Sources")) except Exception: module_logger.exception("message") def createTabs(self, tab): """Create tabs.""" self.tabs = QTabWidget() self.createFormGroupIntro() self.createFormGroupMapstats() self.createFormGroupMapBox() self.createFormGroupMapLandscape() self.createFormGroupVetoes() # Add tabs self.tabs.addTab(self.formGroupIntro, _("Intros")) self.tabs.addTab(self.formGroupMapstats, _("Mapstats")) self.tabs.addTab(self.formGroupMapBox, _("Box Map Icons")) self.tabs.addTab(self.formGroupMapLandscape, _("Landscape Map Icons")) self.tabs.addTab(self.formGroupVetoes, _("Veto Icons")) table = dict() table['intro'] = 0 table['mapstats'] = 1 table['mapicons_box'] = 2 table['mapicons_landscape'] = 3 table['vetoes'] = 4 self.tabs.setCurrentIndex( table.get(tab, SubwindowBrowserSources.current_tab)) self.tabs.currentChanged.connect(self.tabChanged) @classmethod def tabChanged(cls, idx): """Save the current tab.""" SubwindowBrowserSources.current_tab = idx def addHotkey(self, ident, label): """Add a hotkey to the layout.""" element = HotkeyLayout( self, ident, label, scctool.settings.config.parser.get("Intros", ident)) self.hotkeys[ident] = element return element def connectHotkeys(self): """Connect the hotkeys.""" for ident, key in self.hotkeys.items(): if ident == 'hotkey_debug': for ident2, key2 in self.hotkeys.items(): if ident == ident2: continue key.modified.connect(key2.check_dublicate) key.modified.connect(self.hotkeyChanged) def hotkeyChanged(self, key, ident): """Handle change of hotkeys.""" self.changed() if (ident == 'hotkey_player1' and self.cb_single_hotkey.isChecked()): self.hotkeys['hotkey_player2'].setData( self.hotkeys['hotkey_player1'].getKey()) if not key: return if ((ident == 'hotkey_player1' and key == self.hotkeys['hotkey_player2'].getKey()['name']) or (ident == 'hotkey_player2' and key == self.hotkeys['hotkey_player1'].getKey()['name'])): self.cb_single_hotkey.setChecked(True) if (ident in ['hotkey_player1', 'hotkey_player2'] and key == self.hotkeys['hotkey_debug'].getKey()['name']): self.hotkeys['hotkey_debug'].clear() def singleHotkeyChanged(self): """Handle single hotkey changed event.""" checked = self.cb_single_hotkey.isChecked() self.hotkeys['hotkey_player2'].setDisabled(checked) if checked: self.hotkeys['hotkey_player2'].setData( self.hotkeys['hotkey_player1'].getKey()) elif (self.hotkeys['hotkey_player1'].getKey() == self.hotkeys['hotkey_player2'].getKey()): self.hotkeys['hotkey_player2'].clear() def createFormGroupMapstats(self): """Create the form group for mapstats.""" self.formGroupMapstats = QWidget() mainLayout = QVBoxLayout() box = QGroupBox(_("General")) layout = QFormLayout() container = QHBoxLayout() self.qb_boxStyle = StyleComboBox( scctool.settings.casting_html_dir + "/src/css/mapstats", "mapstats") self.qb_boxStyle.connect2WS(self.controller, 'mapstats') label = QLabel(_("Style:")) label.setMinimumWidth(120) button = QPushButton(_("Show in Browser")) button.clicked.connect(lambda: self.openHTML( scctool.settings.casting_html_dir + "/mapstats.html")) container.addWidget(self.qb_boxStyle, 2) container.addWidget(button, 1) layout.addRow(label, container) self.cb_mappool = QComboBox() self.cb_mappool.addItem(_("Current Ladder Map Pool")) self.cb_mappool.addItem(_("Custom Map Pool (defined below)")) self.cb_mappool.addItem(_("Currently entered Maps only")) self.cb_mappool.setCurrentIndex( self.controller.mapstatsManager.getMapPoolType()) self.cb_mappool.currentIndexChanged.connect(self.changed) layout.addRow(QLabel(_("Map Pool:")), self.cb_mappool) self.cb_autoset_map = QCheckBox(_("Select the next map automatically")) self.cb_autoset_map.setChecked( scctool.settings.config.parser.getboolean("Mapstats", "autoset_next_map")) self.cb_autoset_map.stateChanged.connect(self.changed) label = QLabel(_("Next Map:")) label.setMinimumWidth(120) layout.addRow(label, self.cb_autoset_map) self.cb_mark_played = QCheckBox(_("Mark already played maps")) self.cb_mark_played.setChecked( scctool.settings.config.parser.getboolean("Mapstats", "mark_played")) self.cb_mark_played.stateChanged.connect(self.changed) label = QLabel(_("Mark:")) label.setMinimumWidth(120) layout.addRow(label, self.cb_mark_played) self.cb_mark_vetoed = QCheckBox(_("Mark vetoed maps")) self.cb_mark_vetoed.setChecked( scctool.settings.config.parser.getboolean("Mapstats", "mark_vetoed")) self.cb_mark_vetoed.stateChanged.connect(self.changed) label = QLabel(" ") label.setMinimumWidth(120) layout.addRow(label, self.cb_mark_vetoed) self.cb_sort_maps = QCheckBox(_("Sort currently entered maps")) self.cb_sort_maps.setChecked( scctool.settings.config.parser.getboolean("Mapstats", "sort_maps")) self.cb_sort_maps.stateChanged.connect(self.changed) label = QLabel(_("Sort:")) label.setMinimumWidth(120) layout.addRow(label, self.cb_sort_maps) box.setLayout(layout) mainLayout.addWidget(box) box = QGroupBox(_("Custom Map Pool")) layout = QGridLayout() self.maplist = QListWidget() self.maplist.setSortingEnabled(True) ls = list(self.controller.mapstatsManager.getCustomMapPool()) self.maplist.addItems(ls) self.maplist.setCurrentItem(self.maplist.item(0)) layout.addWidget(self.maplist, 0, 0, 3, 1) qb_add = QPushButton() pixmap = QIcon(scctool.settings.getResFile('add.png')) qb_add.setIcon(pixmap) qb_add.clicked.connect(self.addMap) layout.addWidget(qb_add, 0, 1) qb_remove = QPushButton() pixmap = QIcon(scctool.settings.getResFile('delete.png')) qb_remove.clicked.connect(self.removeMap) qb_remove.setIcon(pixmap) layout.addWidget(qb_remove, 1, 1) self.sc_removeMap = QShortcut(QKeySequence("Del"), self) self.sc_removeMap.setAutoRepeat(False) self.sc_removeMap.activated.connect(self.removeMap) box.setLayout(layout) mainLayout.addWidget(box) mainLayout.addItem( QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)) self.formGroupMapstats.setLayout(mainLayout) def addMap(self): """Add a map to the list.""" maplist = list(scctool.settings.maps) for i in range(self.maplist.count()): sc2map = str(self.maplist.item(i).text()) if sc2map in maplist: maplist.remove(sc2map) if len(maplist) > 0: sc2map, ok = QInputDialog.getItem(self, _('Add Map'), _('Please select a map') + ':', maplist, editable=False) if ok: self.__dataChanged = True item = QListWidgetItem(sc2map) self.maplist.addItem(item) self.maplist.setCurrentItem(item) else: QMessageBox.information( self, _("No maps available"), _('All available maps have already been added.')) def removeMap(self): """Remove a map from the list.""" item = self.maplist.currentItem() if item: self.maplist.takeItem(self.maplist.currentRow()) self.__dataChanged = True def createFormGroupMapBox(self): """Create a QWidget for boxed map icons.""" self.formGroupMapBox = QWidget() mainLayout = QVBoxLayout() box = QGroupBox(_("General")) layout = QFormLayout() container = QHBoxLayout() self.qb_boxStyle = StyleComboBox( scctool.settings.casting_html_dir + "/src/css/mapicons_box", "mapicons_box") self.qb_boxStyle.connect2WS(self.controller, 'mapicons_box') label = QLabel(_("Style:")) label.setMinimumWidth(120) button = QPushButton(_("Show in Browser")) button.clicked.connect(lambda: self.openHTML( scctool.settings.casting_html_dir + "/mapicons_box_1.html")) container.addWidget(self.qb_boxStyle, 2) container.addWidget(button, 1) layout.addRow(label, container) self.sb_padding_box = QDoubleSpinBox() self.sb_padding_box.setRange(0, 50) self.sb_padding_box.setDecimals(1) self.sb_padding_box.setValue( scctool.settings.config.parser.getfloat("MapIcons", "padding_box")) self.sb_padding_box.setSuffix(" " + _("Pixel")) self.sb_padding_box.valueChanged.connect( lambda x: self.changePadding('box', x)) layout.addRow(QLabel(_("Icon Padding:") + " "), self.sb_padding_box) box.setLayout(layout) mainLayout.addWidget(box) options = self.controller.matchControl.scopes self.scope_box = dict() for idx in range(3): self.scope_box[idx] = ScopeGroupBox( _("Icon Set {} Scope".format(idx + 1)), options, f'box_{idx + 1}', self.controller, self) self.scope_box[idx].dataModified.connect(self.changed) mainLayout.addWidget(self.scope_box[idx]) mainLayout.addItem( QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)) self.formGroupMapBox.setLayout(mainLayout) def createFormGroupVetoes(self): """Create a QWidget for veto icons.""" self.formGroupVetoes = QWidget() mainLayout = QVBoxLayout() box = QGroupBox(_("General")) layout = QFormLayout() container = QHBoxLayout() self.qb_boxStyle = StyleComboBox( scctool.settings.casting_html_dir + "/src/css/vetoes", "vetoes") self.qb_boxStyle.connect2WS(self.controller, 'vetoes') label = QLabel(_("Style:")) label.setMinimumWidth(120) button = QPushButton(_("Show in Browser")) button.clicked.connect(lambda: self.openHTML( scctool.settings.casting_html_dir + "/vetoes.html")) container.addWidget(self.qb_boxStyle, 2) container.addWidget(button, 1) layout.addRow(label, container) self.sb_padding_box = QDoubleSpinBox() self.sb_padding_box.setRange(0, 50) self.sb_padding_box.setDecimals(1) self.sb_padding_box.setValue( scctool.settings.config.parser.getfloat("Vetoes", "padding")) self.sb_padding_box.setSuffix(" " + _("Pixel")) self.sb_padding_box.valueChanged.connect( lambda x: self.changePadding('vetoes', x)) layout.addRow(QLabel(_("Icon Padding:") + " "), self.sb_padding_box) box.setLayout(layout) mainLayout.addWidget(box) mainLayout.addItem( QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)) self.formGroupVetoes.setLayout(mainLayout) def createFormGroupMapLandscape(self): """Create a QWidget for the landscape map icons.""" self.formGroupMapLandscape = QWidget() mainLayout = QVBoxLayout() box = QGroupBox(_("General")) layout = QFormLayout() container = QHBoxLayout() self.qb_boxStyle = StyleComboBox( scctool.settings.casting_html_dir + "/src/css/mapicons_landscape", "mapicons_landscape") self.qb_boxStyle.connect2WS(self.controller, 'mapicons_landscape') label = QLabel(_("Style:")) label.setMinimumWidth(120) button = QPushButton(_("Show in Browser")) button.clicked.connect(lambda: self.openHTML( scctool.settings.casting_html_dir + "/mapicons_landscape_1.html")) container.addWidget(self.qb_boxStyle, 2) container.addWidget(button, 1) layout.addRow(label, container) self.sb_padding_landscape = QDoubleSpinBox() self.sb_padding_landscape.setRange(0, 50) self.sb_padding_landscape.setDecimals(1) self.sb_padding_landscape.setValue( scctool.settings.config.parser.getfloat("MapIcons", "padding_landscape")) self.sb_padding_landscape.setSuffix(" " + _("Pixel")) self.sb_padding_landscape.valueChanged.connect( lambda x: self.changePadding('landscape', x)) layout.addRow(QLabel(_("Icon Padding:") + " "), self.sb_padding_landscape) box.setLayout(layout) mainLayout.addWidget(box) options = self.controller.matchControl.scopes self.scope_landscape = dict() for idx in range(3): self.scope_landscape[idx] = ScopeGroupBox( _("Icon Set {} Scope".format(idx + 1)), options, f'landscape_{idx + 1}', self.controller, self) self.scope_landscape[idx].dataModified.connect(self.changed) mainLayout.addWidget(self.scope_landscape[idx]) mainLayout.addItem( QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)) self.formGroupMapLandscape.setLayout(mainLayout) def createFormGroupIntro(self): """Create forms for websocket connection to intro.""" self.formGroupIntro = QWidget() mainLayout = QVBoxLayout() box = QGroupBox(_("Style")) layout = QHBoxLayout() styleqb = StyleComboBox( scctool.settings.casting_html_dir + "/src/css/intro", "intro") styleqb.connect2WS(self.controller, 'intro') button = QPushButton(_("Show in Browser")) button.clicked.connect(lambda: self.openHTML( scctool.settings.casting_html_dir + "/intro.html")) layout.addWidget(styleqb, 2) layout.addWidget(button, 1) box.setLayout(layout) mainLayout.addWidget(box) self.behaviorIntroBox = QGroupBox(_("Behavior")) layout = QVBoxLayout() self.cb_hardcode_players = QCheckBox( _("Read player names and order in 1vs1 mode from SCCT instead of SC2" )) self.cb_hardcode_players.setChecked( scctool.settings.config.parser.getboolean("Intros", "hardcode_players")) self.cb_hardcode_players.stateChanged.connect(self.changed) layout.addWidget(self.cb_hardcode_players) self.behaviorIntroBox.setLayout(layout) mainLayout.addWidget(self.behaviorIntroBox) self.hotkeyBox = QGroupBox(_("Hotkeys")) layout = QVBoxLayout() self.controller.websocketThread.unregister_hotkeys(force=True) self.cb_single_hotkey = QCheckBox( _("Use a single hotkey for both players")) self.cb_single_hotkey.stateChanged.connect(self.singleHotkeyChanged) layout.addWidget(self.cb_single_hotkey) self.hotkeys = dict() layout.addLayout(self.addHotkey("hotkey_player1", _("Player 1"))) layout.addLayout(self.addHotkey("hotkey_player2", _("Player 2"))) layout.addLayout(self.addHotkey("hotkey_debug", _("Debug"))) self.cb_single_hotkey.setChecked(self.hotkeys['hotkey_player1'].getKey( ) == self.hotkeys['hotkey_player2'].getKey()) self.connectHotkeys() label = QLabel( _("Player 1 is always the player your observer" " camera is centered on at start of a game.")) layout.addWidget(label) self.hotkeyBox.setLayout(layout) mainLayout.addWidget(self.hotkeyBox) self.introBox = QGroupBox(_("Animation")) layout = QFormLayout() self.cb_animation = QComboBox() animation = scctool.settings.config.parser.get("Intros", "animation") currentIdx = 0 idx = 0 options = dict() options['Fly-In'] = _("Fly-In") options['Slide'] = _("Slide") options['Fanfare'] = _("Fanfare") for key, item in options.items(): self.cb_animation.addItem(item, key) if (key == animation): currentIdx = idx idx += 1 self.cb_animation.setCurrentIndex(currentIdx) self.cb_animation.currentIndexChanged.connect(self.changed) label = QLabel(_("Animation:") + " ") label.setMinimumWidth(120) layout.addRow(label, self.cb_animation) self.sb_displaytime = QDoubleSpinBox() self.sb_displaytime.setRange(0, 10) self.sb_displaytime.setDecimals(1) self.sb_displaytime.setValue( scctool.settings.config.parser.getfloat("Intros", "display_time")) self.sb_displaytime.setSuffix(" " + _("Seconds")) self.sb_displaytime.valueChanged.connect(self.changed) layout.addRow(QLabel(_("Display Duration:") + " "), self.sb_displaytime) self.sl_sound = QSlider(Qt.Horizontal) self.sl_sound.setMinimum(0) self.sl_sound.setMaximum(20) self.sl_sound.setValue( scctool.settings.config.parser.getint("Intros", "sound_volume")) self.sl_sound.setTickPosition(QSlider.TicksBothSides) self.sl_sound.setTickInterval(1) self.sl_sound.valueChanged.connect(self.changed) layout.addRow(QLabel(_("Sound Volume:") + " "), self.sl_sound) self.introBox.setLayout(layout) mainLayout.addWidget(self.introBox) self.ttsBox = QGroupBox(_("Text-to-Speech")) layout = QFormLayout() self.cb_tts_active = QCheckBox() self.cb_tts_active.setChecked( scctool.settings.config.parser.getboolean("Intros", "tts_active")) self.cb_tts_active.stateChanged.connect(self.changed) label = QLabel(_("Activate Text-to-Speech:") + " ") label.setMinimumWidth(120) layout.addRow(label, self.cb_tts_active) self.icons = {} self.icons['MALE'] = QIcon(scctool.settings.getResFile('male.png')) self.icons['FEMALE'] = QIcon(scctool.settings.getResFile('female.png')) self.cb_tts_voice = QComboBox() currentIdx = 0 idx = 0 tts_voices = self.controller.tts.getVoices() tts_voice = scctool.settings.config.parser.get("Intros", "tts_voice") for voice in tts_voices: self.cb_tts_voice.addItem(self.icons[voice['ssmlGender']], ' ' + voice['name'], voice['name']) if (voice['name'] == tts_voice): currentIdx = idx idx += 1 self.cb_tts_voice.setCurrentIndex(currentIdx) self.cb_tts_voice.currentIndexChanged.connect(self.changed) layout.addRow(QLabel(_("Voice:") + " "), self.cb_tts_voice) self.ttsBox.setStyleSheet("QComboBox { combobox-popup: 0; }") self.ttsBox.setLayout(layout) mainLayout.addWidget(self.ttsBox) self.sb_tts_pitch = QDoubleSpinBox() self.sb_tts_pitch.setRange(-20, 20) self.sb_tts_pitch.setDecimals(2) self.sb_tts_pitch.setValue( scctool.settings.config.parser.getfloat("Intros", "tts_pitch")) self.sb_tts_pitch.valueChanged.connect(self.changed) layout.addRow(QLabel(_("Pitch:") + " "), self.sb_tts_pitch) self.sb_tts_rate = QDoubleSpinBox() self.sb_tts_rate.setRange(0.25, 4.00) self.sb_tts_rate.setSingleStep(0.1) self.sb_tts_rate.setDecimals(2) self.sb_tts_rate.setValue( scctool.settings.config.parser.getfloat("Intros", "tts_rate")) self.sb_tts_rate.valueChanged.connect(self.changed) layout.addRow(QLabel(_("Rate:") + " "), self.sb_tts_rate) self.cb_tts_scope = QComboBox() scope = scctool.settings.config.parser.get("Intros", "tts_scope") currentIdx = 0 idx = 0 options = self.controller.tts.getOptions() for key, item in options.items(): self.cb_tts_scope.addItem(item['desc'], key) if (key == scope): currentIdx = idx idx += 1 self.cb_tts_scope.setCurrentIndex(currentIdx) self.cb_tts_scope.currentIndexChanged.connect(self.changed) layout.addRow(QLabel(_("Line:") + " "), self.cb_tts_scope) self.sl_tts_sound = QSlider(Qt.Horizontal) self.sl_tts_sound.setMinimum(0) self.sl_tts_sound.setMaximum(20) self.sl_tts_sound.setValue( scctool.settings.config.parser.getint("Intros", "tts_volume")) self.sl_tts_sound.setTickPosition(QSlider.TicksBothSides) self.sl_tts_sound.setTickInterval(1) self.sl_tts_sound.valueChanged.connect(self.changed) layout.addRow(QLabel(_("Sound Volume:") + " "), self.sl_tts_sound) text = _( "Text-to-Speech provided by Google-Cloud is paid for " "by StarCraft Casting Tool Patrons. To keep this service up " "consider becoming a <a href='{patreon}'>Patron</a> yourself. " "You can test all voices at {tts}.") patreon = 'https://www.patreon.com/StarCraftCastingTool' url = 'https://cloud.google.com/text-to-speech/' tts = "<a href='{}'>cloud.google.com/text-to-speech</a>" tts = tts.format(url) label = QLabel(text.format(patreon=patreon, tts=tts)) label.setAlignment(Qt.AlignJustify) label.setOpenExternalLinks(True) label.setWordWrap(True) label.setMargin(5) layout.addRow(label) mainLayout.addItem( QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)) self.formGroupIntro.setLayout(mainLayout) def createButtonGroup(self): """Create buttons.""" try: layout = QHBoxLayout() layout.addWidget(QLabel("")) buttonCancel = QPushButton(_('Cancel')) buttonCancel.clicked.connect(self.closeWindow) layout.addWidget(buttonCancel) buttonSave = QPushButton(_('&Save && Close')) buttonSave.setToolTip(_("Shortcut: {}").format("Ctrl+S")) self.shortcut = QShortcut(QKeySequence("Ctrl+S"), self) self.shortcut.setAutoRepeat(False) self.shortcut.activated.connect(self.saveCloseWindow) buttonSave.clicked.connect(self.saveCloseWindow) layout.addWidget(buttonSave) self.buttonGroup = layout except Exception: module_logger.exception("message") def changed(self, *values): """Handle changed data.""" self.__dataChanged = True def saveData(self): """Save the data to config.""" if (self.__dataChanged): self.saveWebsocketdata() maps = list() for i in range(self.maplist.count()): maps.append(str(self.maplist.item(i).text()).strip()) self.controller.mapstatsManager.setCustomMapPool(maps) self.controller.mapstatsManager.setMapPoolType( self.cb_mappool.currentIndex()) scctool.settings.config.parser.set( "Mapstats", "autoset_next_map", str(self.cb_autoset_map.isChecked())) scctool.settings.config.parser.set( "Mapstats", "mark_played", str(self.cb_mark_played.isChecked())) scctool.settings.config.parser.set( "Mapstats", "mark_vetoed", str(self.cb_mark_vetoed.isChecked())) scctool.settings.config.parser.set( "Mapstats", "sort_maps", str(self.cb_sort_maps.isChecked())) scctool.settings.config.parser.set( "Intros", "hardcode_players", str(self.cb_hardcode_players.isChecked())) self.controller.mapstatsManager.sendMapPool() self.mainWindow.updateAllMapButtons() for idx in range(3): scctool.settings.config.parser.set( "MapIcons", "scope_box_{}".format(idx + 1), self.scope_box[idx].getScope()) scctool.settings.config.parser.set( "MapIcons", "scope_landscape_{}".format(idx + 1), self.scope_landscape[idx].getScope()) self.controller.matchMetaDataChanged() self.__dataChanged = False # self.controller.refreshButtonStatus() def saveWebsocketdata(self): """Save Websocket data.""" for ident, key in self.hotkeys.items(): string = scctool.settings.config.dumpHotkey(key.getKey()) scctool.settings.config.parser.set("Intros", ident, string) scctool.settings.config.parser.set("Intros", "display_time", str(self.sb_displaytime.value())) scctool.settings.config.parser.set("Intros", "sound_volume", str(self.sl_sound.value())) scctool.settings.config.parser.set( "Intros", "animation", self.cb_animation.currentData().strip()) scctool.settings.config.parser.set( "Intros", "tts_voice", '' if self.cb_tts_voice.currentData() is None else self.cb_tts_voice.currentData().strip()) scctool.settings.config.parser.set( "Intros", "tts_scope", self.cb_tts_scope.currentData().strip()) scctool.settings.config.parser.set("Intros", "tts_active", str(self.cb_tts_active.isChecked())) scctool.settings.config.parser.set("Intros", "tts_volume", str(self.sl_tts_sound.value())) scctool.settings.config.parser.set("Intros", "tts_pitch", str(self.sb_tts_pitch.value())) scctool.settings.config.parser.set("Intros", "tts_rate", str(self.sb_tts_rate.value())) def openHTML(self, file): """Open file in browser.""" self.controller.openURL(scctool.settings.getAbsPath(file)) def changePadding(self, scope, padding): """Change the padding.""" if scope == 'vetoes': scctool.settings.config.parser.set("Vetoes", "padding", str(padding)) self.controller.websocketThread.changePadding("vetoes", padding) else: scctool.settings.config.parser.set("MapIcons", f"padding_{scope}", str(padding)) self.controller.websocketThread.changePadding( f"mapicons_{scope}", padding) def saveCloseWindow(self): """Save and close window.""" self.saveData() self.closeWindow() def closeWindow(self): """Close window without save.""" self.passEvent = True self.close() def closeEvent(self, event): """Handle close event.""" try: if (not self.__dataChanged): self.controller.updateHotkeys() event.accept() return if (not self.passEvent): if (self.isMinimized()): self.showNormal() buttonReply = QMessageBox.question( self, _('Save data?'), _("Do you want to save the data?"), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if buttonReply == QMessageBox.Yes: self.saveData() self.controller.updateHotkeys() event.accept() except Exception: module_logger.exception("message")
class FunctionsMenu(QWidget): def __init__(self): super().__init__() self.layout = QGridLayout() self.setLayout(self.layout) row_hight = 30 margins = self.layout.contentsMargins() margins.setTop(2 * row_hight + self.layout.spacing()) margins.setLeft(20) self.layout.setContentsMargins(margins) # Initializing GUI elements self.ipp = QRadioButton() self.ippcp = QRadioButton() self.select_ipp = QPushButton('Select package') self.select_ippcp = QPushButton('Select package') self.select_ipp.package = utils.IPP self.select_ippcp.package = utils.IPPCP self.lib_var_list = QComboBox(self) self.search = QLineEdit(self) self.selected_libraries_list = QListWidget(self) self.auto_build_button = QPushButton('Autobuild') self.current_functions_list = {} self.functions_list = { 'Classical IPP': {}, 'IPP TL': {}, 'IPP Cryptography': {} } # Preparing elements by giving initial values, etc self.ipp.setText('IPP ver. None') self.ippcp.setText('IPP Cryptography ver. None') self.search.setPlaceholderText('Search...') self.ipp.setDisabled(True) self.ippcp.setDisabled(True) self.auto_build_button.setDisabled(True) self.lib_var_list.activated[str].connect(self.on_theme_selected) self.search.textEdited.connect(self.on_search) self.selected_libraries_list.itemClicked.connect(self.on_item_selected) self.auto_build_button.clicked.connect(self.on_build_pressed) self.select_ipp.clicked.connect(self.on_select) self.select_ippcp.clicked.connect(self.on_select) self.ipp.toggled.connect(self.on_switch) # Setting all widgets in their places self.layout.addWidget(self.ipp, 0, 0, 1, 3) self.layout.addWidget(self.ippcp, 1, 0, 1, 3) self.layout.addWidget(self.select_ipp, 0, 3) self.layout.addWidget(self.select_ippcp, 1, 3) self.layout.addWidget(self.lib_var_list, 2, 0, 1, 4) self.layout.addWidget(self.search, 3, 0, 1, 4) self.layout.addWidget(self.selected_libraries_list, 4, 0, 1, 4) self.layout.addWidget(self.auto_build_button, 5, 0, 1, 4) self.select_ipp.setFixedHeight(row_hight) self.select_ippcp.setFixedHeight(row_hight) self.lib_var_list.setFixedHeight(row_hight) path_to_package = self.get_path_to_package() if path_to_package: package = utils.IPPCP if re.compile('.*ippcp.*').match( path_to_package) else utils.IPP if self.set_package(package, path_to_package): self.init_menu() def init_menu(self): self.ipp.toggled.disconnect(self.on_switch) self.tl_selected = False if self.ipp.isEnabled(): package = utils.IPP self.init_functions(utils.IPP, settings.CONFIGS[utils.IPP]['Path']) self.ipp.setChecked(True) if self.ippcp.isEnabled(): self.init_functions(utils.IPPCP, settings.CONFIGS[utils.IPPCP]['Path']) if not self.ipp.isEnabled(): package = utils.IPPCP self.ippcp.setChecked(True) self.show_menu(package) self.ipp.toggled.connect(self.on_switch) def set_package(self, package, path): if self.check_package(package, path): settings.CONFIGS[package]['Path'] = path if package == utils.IPP: self.ipp_version = self.get_version(path, package) self.ipp.setText('IPP ver. ' + self.ipp_version) self.ipp.setEnabled(True) else: self.ippcp_version = self.get_version(path, package) self.ippcp.setText('IPP Cryptography ver. ' + self.ippcp_version) self.ippcp.setEnabled(True) return True elif path: if package == utils.IPP: QMessageBox.information( self, 'ERROR!', 'Incorrect Intel® Integrated Performance Primitives package path!' ) else: QMessageBox.information( self, 'ERROR!', 'Incorrect Intel® Integrated Performance Primitives Cryptography package path!' ) return False def check_package(self, package, path): if not self.check_batch(package, path): return False if os.path.exists(os.path.join(path, 'include')): for header in os.listdir(os.path.join(path, 'include')): if get_mode_and_domain(header): break else: return False if utils.HOST_SYSTEM == MACOSX: self.intel64_libs_path = path else: self.intel64_libs_path = self.get_path_to_libs(path, 'intel64') self.ia32_libs_path = self.get_path_to_libs(path, 'ia32') return True if self.check_libs(self.ia32_libs_path) or \ self.check_libs(self.intel64_libs_path) else False def check_batch(self, package, path): return os.path.exists(os.path.join(path, 'bin', package.lower() + 'vars' + BATCH_EXTENSIONS[utils.HOST_SYSTEM])) \ or os.path.exists(os.path.join(path, 'env', package.lower() + 'vars' + BATCH_EXTENSIONS[utils.HOST_SYSTEM])) def get_path_to_libs(self, path, arch): if os.path.exists(os.path.join(path, 'lib', arch)): return os.path.join(path, 'lib', arch) elif os.path.exists( os.path.join(path, 'lib', arch + '_' + utils.HOST_SYSTEM.lower()[:3])): return os.path.join(path, 'lib', arch + '_' + utils.HOST_SYSTEM.lower()[:3]) else: return '' def check_libs(self, path): if path: for lib in os.listdir(path): if STATIC_LIBRARIES_EXTENSIONS[utils.HOST_SYSTEM] in lib: return True return False def on_select(self): package = self.sender().package while True: path = QFileDialog.getExistingDirectory( self, 'Select ' + package + ' package') if not path: return if self.set_package(package, path): break self.init_functions(package, path) if package == utils.IPP: if not self.ipp.isChecked() and not self.ippcp.isChecked(): self.ipp.toggled.disconnect(self.on_switch) self.ipp.setChecked(True) self.ipp.toggled.connect(self.on_switch) else: if not self.ipp.isChecked() and not self.ippcp.isChecked(): self.ippcp.setChecked(True) for config in settings.CONFIGS[package].keys(): if config != 'Path' and config != 'functions_list': settings.CONFIGS[package][config] = False settings.CONFIGS[package]['functions_list'].clear() if package == utils.IPP and self.ipp.isChecked() or \ package == utils.IPPCP and self.ippcp.isChecked(): self.parent.receiver.set_configs(package) self.parent.receiver.functions_names.clear() self.parent.receiver.functions_list.clear() self.show_menu(package) self.parent.receiver.on_block() def on_switch(self): if self.ipp.isChecked(): package = utils.IPP self.parent.receiver.get_configs(utils.IPPCP) else: package = utils.IPPCP self.parent.receiver.get_configs(utils.IPP) self.parent.receiver.set_configs(package) self.show_menu(package) self.parent.receiver.add_items(self.parent.receiver.functions_names) self.parent.receiver.on_block() def on_theme_selected(self, text): self.add_items(self.current_functions_list.get(text)) self.on_search(self.search.text()) def on_search(self, search_request): if self.current_functions_list: self.add_items([ entry for entry in self.current_functions_list.get( self.lib_var_list.currentText()) if search_request.upper() in entry.upper() ]) def on_item_selected(self, item): self.selected_libraries_list.setCurrentItem(item) def on_build_pressed(self): if self.ipp.isChecked(): package = utils.IPP version = self.ipp_version else: package = utils.IPPCP version = self.ippcp_version os.environ[package + 'ROOT'] = settings.CONFIGS[package]['Path'] self.get_path_to_cnl(settings.CONFIGS[package]['Path'], version) while not os.path.exists( os.path.join( utils.COMPILERS_AND_LIBRARIES_PATH, utils.HOST_SYSTEM.lower(), 'bin', 'compilervars' + BATCH_EXTENSIONS[utils.HOST_SYSTEM])): QMessageBox.information(self, 'ERROR!', 'Incorrect compilers_and_libraries path!') cnl_path = QFileDialog.getExistingDirectory( self, 'Select compilers_and_libraries directory') if not cnl_path: return utils.COMPILERS_AND_LIBRARIES_PATH = cnl_path information = self.parent.get_library_information() library_path = QFileDialog.getExistingDirectory(self, 'Save DLL to...') if not library_path: return success = False self.parent.set_disabled(True) QMessageBox.information( self, 'Build', 'Building will start after this window is closed. ' 'Please wait until process is done.') if information['ia32']: success = tool.core.build( package, information['host_system'], information['target_system'], information['functions'], library_path, information['library_name'], tool.utils.IA32, information['threading'] == 'Multi-threaded', tool.utils.COMPILERS_AND_LIBRARIES_PATH, threading_layer_type=information['threading_layer_type']) if information['intel64']: success = tool.core.build( package, information['host_system'], information['target_system'], information['functions'], library_path, information['library_name'], tool.utils.INTEL64, information['threading'] == 'Multi-threaded', tool.utils.COMPILERS_AND_LIBRARIES_PATH, threading_layer_type=information['threading_layer_type']) self.parent.set_disabled(False) QMessageBox.information( self, 'Success' if success else 'Failure', 'Build completed!' if success else 'Build failed!') def add_items(self, items): """ Sorts and adds items to list view :param items: list of strings """ self.selected_libraries_list.clear() if items: items.sort() self.selected_libraries_list.addItems(items) self.selected_libraries_list.setCurrentItem( self.selected_libraries_list.item(0)) self.selected_libraries_list.repaint() def add_item(self, function_name): """ Adds function to left list :param function_name: """ self.operation(list.append, function_name) self.add_items( self.current_functions_list.get(self.lib_var_list.currentText())) self.on_search(self.search.text()) def remove_item(self, item): """ Removes item from left list """ if item is None: return None self.operation(list.remove, item) self.add_items( self.current_functions_list.get(self.lib_var_list.currentText())) self.on_search(self.search.text()) def operation(self, action, function_name): for mode in FUNCTIONS_LIST.keys(): for domain in FUNCTIONS_LIST[mode].keys(): if function_name in FUNCTIONS_LIST[mode][domain]: action(self.functions_list[mode][domain], function_name) return def init_func_list(self): """ Taking all domains and their functions """ self.lib_var_list.clear() self.lib_var_list.addItems( [entry for entry in self.current_functions_list.keys()]) def init_functions(self, package, path): if package == utils.IPP: FUNCTIONS_LIST['Classical IPP'].clear() FUNCTIONS_LIST['IPP TL'].clear() get_functions_from_headers(path) self.functions_list['Classical IPP'] = copy.deepcopy( FUNCTIONS_LIST['Classical IPP']) self.functions_list['IPP TL'] = copy.deepcopy( FUNCTIONS_LIST['IPP TL']) else: FUNCTIONS_LIST['IPP Cryptography'].clear() get_functions_from_headers(path) self.functions_list['IPP Cryptography'] = copy.deepcopy( FUNCTIONS_LIST['IPP Cryptography']) self.threaded_functions = [ item for sublist in self.functions_list['IPP TL'].values() for item in sublist ] def show_menu(self, package): if package == utils.IPP: if not self.tl_selected: self.current_functions_list = self.functions_list[ 'Classical IPP'] else: self.current_functions_list = self.functions_list['IPP TL'] else: self.current_functions_list = self.functions_list[ 'IPP Cryptography'] self.init_func_list() self.add_items( self.current_functions_list.get(self.lib_var_list.currentText())) def get_path_to_package(self): dir_path = os.path.dirname(os.path.realpath(__file__)) if re.compile( utils.PATH_TO_PACKAGE_REGULAR_EXPRESSION).match(dir_path): return re.match(utils.PATH_TO_PACKAGE_REGULAR_EXPRESSION, dir_path).group('path') else: return '' def get_version(self, path, package): path_to_header = os.path.join(path, 'include', package.lower() + 'version.h') if os.path.exists(path_to_header): header = open(path_to_header, 'r') lines = header.readlines() for line in lines: if re.compile(utils.VERSION_REGULAR_EXPRESSION).match(line): return re.match(utils.VERSION_REGULAR_EXPRESSION, line).group('ver') return 'None' def get_path_to_cnl(self, path, version): if re.compile(utils.PATH_TO_CNL_REGULAR_EXPRESSION).match(path): utils.COMPILERS_AND_LIBRARIES_PATH = re.match( utils.PATH_TO_CNL_REGULAR_EXPRESSION, path).group('cnl') elif re.compile(utils.PATH_TO_ONEAPI_REGULAR_EXPRESSION).match(path): oneapi_path = re.match(utils.PATH_TO_ONEAPI_REGULAR_EXPRESSION, path).group('oneapi') utils.COMPILERS_AND_LIBRARIES_PATH = os.path.join( oneapi_path, 'compiler', version)
class PopUpDialog(QDialog): def __init__(self, title="Test", label='Value1', value=1.0, listMode=False): super(PopUpDialog, self).__init__() logger.debug(title) logger.debug(label) logger.debug(value) self.title = title self.label = label self.value = value self.result = None if not (len(label) == len(value)) and not listMode: raise Exception("Number of labels different to number of values") self.initUI(listMode) def tr(self, string_to_translate): """ Translate a string using the QCoreApplication translation framework @param: string_to_translate: a unicode string @return: the translated unicode string if it was possible to translate """ return str( QtCore.QCoreApplication.translate('PopUpDialog', string_to_translate)) def initUI(self, listMode): vbox = QVBoxLayout(self) top = QFrame(self) top.setFrameShape(QFrame.StyledPanel) bottom = QFrame(self) bottom.setFrameShape(QFrame.StyledPanel) grid1 = QGridLayout() grid1.setSpacing(10) self.lineLabel = [] self.lineEdit = [] self.listMode = listMode if not listMode: for i in range(len(self.label)): self.lineLabel.append(QLabel(self.label[i])) self.lineEdit.append(QLineEdit('%s' % self.value[i])) grid1.addWidget(self.lineLabel[i], i, 0) grid1.addWidget(self.lineEdit[i], i, 1) else: self.lineLabel = QListWidget() self.lineLabel.addItems(self.label) grid1.addWidget(self.lineLabel) top.setLayout(grid1) grid2 = QGridLayout() grid2.setSpacing(5) okButton = QPushButton(self.tr("OK")) cancelButton = QPushButton(self.tr("Cancel")) okButton.clicked.connect(self.cbOK) self.lineLabel.itemDoubleClicked.connect(self.cbOK) cancelButton.clicked.connect(self.cbCancel) grid2.addWidget(okButton, 0, 2) grid2.addWidget(cancelButton, 0, 3) bottom.setLayout(grid2) vbox.addWidget(top) vbox.addWidget(bottom) self.setLayout(vbox) self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint) self.setWindowTitle(self.title) iconWT = QIcon() iconWT.addPixmap(QPixmap(":images/opencv.ico"), QIcon.Normal, QIcon.Off) self.setWindowIcon(QIcon(iconWT)) self.exec_() def cbOK(self): self.result = [] if not self.listMode: for lineEdit in self.lineEdit: self.result.append(lineEdit.text()) else: self.result = self.lineLabel.currentItem().text() logger.debug(self.result) self.close() def cbCancel(self): logger.debug('Cancel') self.close()
class SearchCity(QDialog): id_signal = pyqtSignal([tuple]) city_signal = pyqtSignal([tuple]) country_signal = pyqtSignal([tuple]) def __init__(self, accurate_url, appid, parent=None): super(SearchCity, self).__init__(parent) self.settings = QSettings() self.delay = 1000 self.search_string = self.tr('Searching...') self.timer = QTimer() self.accurate_url = accurate_url self.suffix = '&type=like&mode=xml' + appid self.layout = QVBoxLayout() self.lineLayout = QHBoxLayout() self.buttonSearch = QPushButton() self.buttonSearch.setIcon(QIcon(':/find')) self.buttonSearch.setToolTip( QCoreApplication.translate( 'Search city button Tooltip', 'Search city', 'Search for the given place' ) ) self.buttonSearch.clicked.connect(self.search) self.buttonMyLocation = QPushButton() self.buttonMyLocation.setIcon(QIcon(':/mylocation')) self.buttonMyLocation.setToolTip( QCoreApplication.translate( 'Search by geolocalisation button tooltip', 'Find my location', 'Automatic search of my place' ) ) self.buttonMyLocation.clicked.connect(self.myLocation) self.line_search = QLineEdit( QCoreApplication.translate( 'Search city dialogue', 'Start typing the city or the geographic ' 'coordinates "latitude, longitude"', 'Default message in the search field' ) ) self.line_search.selectAll() self.listWidget = QListWidget() self.status = QLabel() self.lineLayout.addWidget(self.line_search) self.lineLayout.addWidget(self.buttonSearch) self.lineLayout.addWidget(self.buttonMyLocation) self.layout.addLayout(self.lineLayout) self.layout.addWidget(self.listWidget) self.layout.addWidget(self.status) self.buttonLayout = QHBoxLayout() self.buttonLayout.addStretch() self.buttonOk = QPushButton(self.tr('&Ok')) self.buttonOk.setEnabled(False) self.buttonCancel = QPushButton(self.tr('&Cancel')) self.buttonLayout.addWidget(self.buttonOk) self.buttonLayout.addWidget(self.buttonCancel) self.layout.addLayout(self.buttonLayout) self.setMinimumWidth(800) self.setLayout(self.layout) self.line_search.returnPressed.connect(self.search) self.line_search.textChanged.connect(self.timer_run) self.buttonOk.clicked.connect(self.accept) self.buttonCancel.clicked.connect(self.reject) self.listWidget.itemSelectionChanged.connect(self.buttonCheck) self.listWidget.itemDoubleClicked['QListWidgetItem *'].connect(self.accept) self.restoreGeometry( self.settings.value("SearchCity/Geometry", QByteArray()) ) self.timer_search = QTimer(self) self.timer_search.timeout.connect(self.search) self.setWindowTitle( QCoreApplication.translate( 'Window title', 'Find a city', 'City search dialogue' ) ) self.status.setText( 'ℹ ' + QCoreApplication.translate( 'Status message', 'Click on "Find my Location" button for automatic geolocation', 'City search dialogue' ) ) def timer_run(self): self.timer_search.start(1000) def closeEvent(self, event): self.settings.setValue( "SearchCity/Geometry", self.saveGeometry() ) def moveEvent(self, event): self.settings.setValue( "SearchCity/Geometry", self.saveGeometry() ) def resizeEvent(self, event): self.settings.setValue( "SearchCity/Geometry", self.saveGeometry() ) def buttonCheck(self): '''Enable OK button if an item is selected.''' row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is not None: self.buttonOk.setEnabled(True) def accept(self): row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is not None: selected_city = item.text() city_list = selected_city.split(' - ') for c in range(len(city_list)): city_list[c] = city_list[c].strip() id_ = 'ID', city_list[0] city = 'City', city_list[1] country = 'Country', city_list[2] self.id_signal[tuple].emit(id_) self.city_signal[tuple].emit(city) self.country_signal[tuple].emit(country) QDialog.accept(self) def thread_terminate(self): if hasattr(self, 'workThread'): if self.workThread.isRunning(): self.workThread.terminate() def myLocation(self): locFound = False loc = QCoreApplication.translate( 'Search city', 'N/A', 'Inserted in search field when the automatic' 'geolocalisation is not available' ) try: page = urllib.request.urlopen('http://ipinfo.io/json', timeout=5) rep = page.read().decode('utf-8') locdic = json.loads(rep) loc = locdic['loc'] locFound = True except (KeyError, urllib.error.HTTPError, timeout) as e: locFound = False logging.critical( 'Error fetching geolocation from http://ipinfo.io/json: ' + str(e) ) if locFound is False: try: data = str(urllib.request.urlopen('http://checkip.dyndns.com/', timeout=5).read()) myip = re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1) url = ( 'http://api.ipstack.com/{}?access_key=1f5f4144cd87a4eda32832dad469b586' .format(myip) ) page = urllib.request.urlopen(url, timeout=5) rep = page.read().decode('utf-8') locdic = json.loads(rep) loc = str(locdic['latitude']) + ',' + str(locdic['longitude']) except (KeyError, urllib.error.HTTPError, timeout) as e: logging.critical( 'Error fetching geolocation from {}: '.format(url) + str(e) ) self.line_search.setText(loc) def search(self): self.timer_search.stop() self.city = (self.line_search.text()) self.thread_terminate() if len(self.city) < 3: self.status.setText( QCoreApplication.translate( 'SearchCity window', 'Please type more than three characters', 'Message in the statusbar' ) ) return self.lista = [] self.errorStatus = False self.buttonOk.setEnabled(False) self.listWidget.clear() self.status.setText(self.search_string) self.workThread = WorkThread(self.accurate_url, self.city, self.suffix) self.workThread.setTerminationEnabled(True) self.workThread.city_signal['QString'].connect(self.addlist) self.workThread.finished.connect(self.result) self.workThread.error['QString'].connect(self.error) self.workThread.searching['QString'].connect(self.searching) self.workThread.started.connect(self.thread_started) self.timer.singleShot(self.delay, self.threadstart) def searching(self, message): '''Display a status message when searching takes a while''' self.status.setText(message) def thread_started(self): '''Force the "searching" status message''' self.status.setText(self.search_string) def threadstart(self): self.workThread.start() def addlist(self, city): logging.debug('Found: ' + str(city)) if city not in self.lista: self.lista.append(city) self.errorStatus = False def error(self, e): self.delay = 2000 logging.error(e) self.status.setText(e) self.adjustSize() self.errorStatus = True def result(self): if self.errorStatus: return if len(self.line_search.text()) < 3: self.thread_terminate() self.status.clear() return self.delay = 1000 # Clear the listWidget elements from an interrupted thread self.listWidget.clear() self.listWidget.addItems(self.lista) number_cities = len(self.lista) cities_text = '' if number_cities == 0: cities_text = self.tr('No results') elif number_cities == 1: cities_text = self.tr('Found {0} city').format(number_cities) elif number_cities > 1: cities_text = self.tr('Found {0} cities').format(number_cities) self.status.setText(cities_text)
class ApplicationGUI(QWidget): # class variables __lecturer_id = None __module_id = None __lecture_id = None __module_list = None """Class used to define GUI components of the application, and enable navigation between pages of the GUI.""" def __init__(self, parent=None): """ Initialises GUI page layout """ super().__init__(parent) self.app_pages = QStackedLayout() self.stack_login_page = QWidget() self.stack_start_page = QWidget() self.stack_camera_feed_page = QWidget() self.login_page_ui() self.start_page_ui() self.camera_feed_page_ui() self.app_pages.addWidget(self.stack_login_page) self.app_pages.addWidget(self.stack_start_page) self.app_pages.addWidget(self.stack_camera_feed_page) def login_page_ui(self): # Page Properties self.stack_login_page.setWindowTitle('Login Page') self.stack_login_page.setFixedSize(600, 400) self.stack_login_page.setStyleSheet('background: #424242') # Label Widgets self.label_login_title = QLabel(self.stack_login_page, text='Login Page') self.label_login_title.setStyleSheet('font-size: 24px; color: white;') self.label_login_title.setGeometry(270, 20, 600, 30) self.label_email = QLabel(text='Email:') self.label_email.setStyleSheet('font-size: 16px; color: white') self.label_password = QLabel(text='Password:'******'font-size: 16px; color: white') self.label_error_message = QLabel(text='') self.label_error_message.setStyleSheet('font-size: 16px; color: red;') # Text Entry Widgets self.entry_email = QLineEdit() self.entry_email.setStyleSheet('color: white; background-color: grey;') self.entry_password = QLineEdit() self.entry_password.setEchoMode(QLineEdit.Password) self.entry_password.setStyleSheet( 'color: white; background-color: grey;') # Button Widgets self.button_login = QPushButton(text='Login') self.button_login.setStyleSheet( 'color: white; background-color: #003366') # Button Widget Signal self.button_login.clicked.connect(self.login) # Grid Layout Widget self.grid_layout_login_page = QGridLayout() self.stack_login_page.setLayout(self.grid_layout_login_page) self.grid_layout_login_page.addWidget(self.label_email, 1, 1, alignment=QtCore.Qt.AlignRight) self.grid_layout_login_page.addWidget(self.entry_email, 1, 2, alignment=QtCore.Qt.AlignLeft) self.grid_layout_login_page.addWidget(self.label_password, 2, 1, alignment=QtCore.Qt.AlignRight) self.grid_layout_login_page.addWidget(self.entry_password, 2, 2, alignment=QtCore.Qt.AlignLeft) self.grid_layout_login_page.addWidget(self.label_error_message, 3, 1, alignment=QtCore.Qt.AlignRight) self.grid_layout_login_page.addWidget(self.button_login, 3, 2, alignment=QtCore.Qt.AlignLeft) def start_page_ui(self): """ GUI Start page, contains components to set both the time and module the system will run for, also contains a button to navigate to the camera feed page.""" # Page Properties self.stack_start_page.setWindowTitle('Start Page') self.stack_start_page.setFixedSize(600, 400) self.stack_start_page.setStyleSheet('background: #424242') # Label Widgets self.label_title = QLabel(self.stack_start_page, text='Face Recognition Attendance System') self.label_title.setStyleSheet('font-size: 24px; color: white;') self.label_title.setGeometry(60, 20, 600, 30) self.label_module = QLabel(text='Module:') self.label_module.setStyleSheet('font-size: 16px; color: white') self.label_timer = QLabel(text='Length of Class (Hours):') self.label_timer.setStyleSheet('font-size: 16px; color: white') # Combobox Widget self.cb_module = QComboBox() self.cb_module.setStyleSheet('color: white; background-color: grey;') # Spin Box Widget self.spin_box_time = QSpinBox() self.spin_box_time.setMinimum(1) self.spin_box_time.setMaximum(24) self.spin_box_time.setStyleSheet( 'color: white; background-color: grey') # Button Widgets self.button_logout = QPushButton(text='Logout') self.button_logout.setStyleSheet( 'color: white; background-color: #003366') self.button_navigate_start = QPushButton(text='Start Recording') self.button_navigate_start.setStyleSheet( 'color: white; background-color: #003366') # Button Widget Signal self.button_logout.clicked.connect(self.logout) self.button_navigate_start.clicked.connect( self.navigate_to_camera_feed_page) # Grid Layout Widget self.grid_layout_start_page = QGridLayout() self.stack_start_page.setLayout(self.grid_layout_start_page) self.grid_layout_start_page.addWidget(self.label_module, 1, 1, alignment=QtCore.Qt.AlignRight) self.grid_layout_start_page.addWidget(self.cb_module, 1, 2, alignment=QtCore.Qt.AlignLeft) self.grid_layout_start_page.addWidget(self.label_timer, 2, 1, alignment=QtCore.Qt.AlignRight) self.grid_layout_start_page.addWidget(self.spin_box_time, 2, 2, alignment=QtCore.Qt.AlignLeft) self.grid_layout_start_page.addWidget(self.button_logout, 3, 1, alignment=QtCore.Qt.AlignRight) self.grid_layout_start_page.addWidget(self.button_navigate_start, 3, 2, alignment=QtCore.Qt.AlignLeft) def camera_feed_page_ui(self): """ GUI Page which displays the camera feed, module which the attendance is being recorded for, and list of students marked as present. Also contains a button to navigate back to the start page. """ # Page Properties self.stack_camera_feed_page.setWindowTitle('Face Detection Page') self.stack_camera_feed_page.setFixedSize(1000, 600) self.stack_camera_feed_page.setStyleSheet('background: #424242') # Button Widgets self.button_navigate_main_menu = QPushButton( text='Cancel and return to Start Page') self.button_navigate_main_menu.setStyleSheet( 'color: white; background-color: #003366') self.button_navigate_main_menu.setGeometry(0, 50, 120, 60) # Button Widget Signal self.button_navigate_main_menu.clicked.connect( self.navigate_to_start_page) # Label Widget self.label_module_title = QLabel('') self.label_module_title.setStyleSheet('font-size: 20px; color: white') # Camera Feed Widget self.camera_feed_widget = CameraFeedWidget() # TODO: List widget of students marked as present self.list_attendance = QListWidget() self.list_attendance.setStyleSheet('font-size: 14px; color: white;') # Page Layout self.camera_feed_page_layout = QGridLayout() self.stack_camera_feed_page.setLayout(self.camera_feed_page_layout) self.camera_feed_page_layout.addWidget(self.camera_feed_widget, 1, 0) self.camera_feed_page_layout.addWidget(self.label_module_title, 0, 1, alignment=QtCore.Qt.AlignTop) self.camera_feed_page_layout.addWidget(self.list_attendance, 1, 1, alignment=QtCore.Qt.AlignTop) self.camera_feed_page_layout.addWidget(self.button_navigate_main_menu, 2, 1) self.setLayout(self.camera_feed_page_layout) def login(self): """ Log in to the application and navigate to the start page """ self.set_lecturer_id( authenticate_lecturer(self.entry_email.text(), self.entry_password.text())) if authenticate_lecturer(self.entry_email.text(), self.entry_password.text()): # clear login page fields self.entry_email.setText('') self.entry_password.setText('') self.label_error_message.setText('') # populate combobox from database self.set_module_list(lecturer_module_list(self.get_lecturer_id())) self.cb_module.addItems(self.get_module_list().values()) # set module id for m_id, title in self.get_module_list().items(): if title == self.cb_module.currentText(): self.set_module_id(m_id) # navigate to different page self.app_pages.setCurrentIndex(1) else: self.label_error_message.setText('Email and Password do not match') def logout(self): self.set_lecture_id(None) self.app_pages.setCurrentIndex(0) self.cb_module.clear() def navigate_to_start_page(self): """ Navigates to the Start page. """ self.list_attendance.clear() self.set_lecture_id(None) self.app_pages.setCurrentIndex(1) self.camera_feed_widget.stop_camera_feed() def navigate_to_camera_feed_page(self): """ Navigates to the Camera feed page. """ self.set_lecture_id( insert_new_lecture(self.get_module_id(), self.get_lecturer_id())) self.label_module_title.setText(self.cb_module.currentText()) self.camera_feed_widget.start_camera_feed( self.convert_to_hours(int(self.spin_box_time.value()))) self.list_attendance.addItems( lecture_attendance_list(self.get_lecture_id())) self.app_pages.setCurrentIndex(2) def convert_to_hours(self, time): converted_time = time * 3600 return converted_time def get_lecturer_id(self): return self.__lecturer_id def get_module_id(self): return self.__module_id def get_lecture_id(self): return self.__lecture_id def get_module_list(self): return self.__module_list def set_lecturer_id(self, new_l_id): self.__lecturer_id = new_l_id def set_module_id(self, new_m_id): self.__module_id = new_m_id def set_lecture_id(self, new_l_id): self.__lecture_id = new_l_id def set_module_list(self, new_m_list): self.__module_list = new_m_list
class MainWindow(QWidget): """ Simple dialog that consists of a Progress Bar and a Button. Clicking on the button results in the start of a timer and updates the progress bar. """ def __init__(self): QWidget.__init__(self) self.setStyleSheet("color: black; background-color: rgb(0,162,232);") self.setGeometry(60,80,500,600) self.setWindowTitle('Watching SVC Files FOR TYPEY-ABC') #button self.button = QPushButton('Start', self) self.button.setStyleSheet("color: black; font-size : 23px; border : 3px solid black") self.button.setGeometry(40, 30, 130, 40) self.button.clicked.connect(self.onButtonClick) #progressbar self.progress = QProgressBar(self) self.progress.setGeometry(40, 100, 420, 15) self.progress.setMaximum(ENV.CYCLE_TIME) #List label list_label = QLabel(self) list_label.setStyleSheet("color: black; font-size : 23px;") list_label.setText("PRINTING LOG") list_label.setGeometry(60, 160, 200, 30) #listbox self.listwidget = QListWidget(self) self.listwidget.setStyleSheet("color: black; border : 3px solid black; font-size : 16px") self.listwidget.setGeometry(40, 200, 420, 300) self.time_label = QLabel(self) self.time_label.setStyleSheet("color: black; font-size : 20px; border : 3px solid black") self.time_label.setText("") self.time_label.setGeometry(40, 520, 300, 30) timer = QTimer(self) timer.timeout.connect(self.showTime) timer.start(1000) self.show() def onButtonClick(self): try: with open(ENV.MASTERFILEPATH + ENV.TYPEY_PRINT): os.remove(ENV.MASTERFILEPATH + ENV.TYPEY_PRINT) print ("Old TYPEY.csv file will be removed and create a new one.") except IOError: print ("New TYPEY.csv file will be created") try: with open(ENV.MASTERFILEPATH + "TypeY_info.csv"): os.remove(ENV.MASTERFILEPATH + "TypeY_info.csv") print ("Old TYPEY_info.csv file will be removed and create a new one.") except IOError: print ("New TYPEY_info.csv file will be created") #for typeY processes print ("======================================OPENING MASTERSHEET EXCEL FILES================================") print ("-------------------------------------- TYPEY MASTERSHEET ------------------------------------") #reading for type 0 files mastersheet = pd.read_excel (ENV.MASTERFILEPATH + ENV.TYPEY_MASTER) records = mastersheet.to_records() self.typeY_Run = [] row_index = 2 for row in records : file = pathlib.Path(ENV.FILEPATH + 'IndexValuePanelData_' + row[1] + ".csv") if file.exists() == True : print (file) print ("---------------THIS FILE EXISTS--------------") index = len(self.typeY_Run) #classify this file is positive or negative self.typeY_Run.append(TYPEY_LOGIC_THREAD.External()) self.typeY_Run[index].countChanged.connect(self.onCountChanged) self.typeY_Run[index].printChanged.connect(self.onPrintChanged) self.typeY_Run[index].src_file_name = row[1] + ".csv" if row[5] == "24HRS" : self.typeY_Run[index].start_hour = 0 self.typeY_Run[index].end_hour = 24 else : self.typeY_Run[index].start_hour = int(row[5]) self.typeY_Run[index].end_hour = int(row[6]) self.typeY_Run[index].start() row_index += 1 def onCountChanged(self, value): self.progress.setValue(value) def onPrintChanged(self, value) : self.listwidget.addItems([value]) def showTime(self) : format = "%H:%M:%S" # Current time in UTC now_gmt = datetime.now(timezone('GMT')) gmt_time = now_gmt.astimezone(timezone('Europe/Moscow')) self.time_label.setText("GMT+3 " + gmt_time.strftime(format))
class CityListDlg(QDialog): citieslist_signal = pyqtSignal([list]) def __init__(self, citylist, accurate_url, appid, parent=None): super(CityListDlg, self).__init__(parent) self.citylist = citylist self.accurate_url = accurate_url self.appid = appid self.listWidget = QListWidget() self.listWidget.addItems(self.citylist) buttonLayout = QVBoxLayout() self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.rejected.connect(self.reject) self.buttonBox.accepted.connect(self.accept) layoutT = QVBoxLayout() layout = QHBoxLayout() layout.addWidget(self.listWidget) layout.addLayout(buttonLayout) for text, slot in ((self.tr("&Add..."), self.add), (self.tr("&Remove..."), self.remove), (self.tr("&Up"), self.up), (self.tr("&Down"), self.down), (self.tr("De&fault"), self.default), (self.tr("&Sort"), self.listWidget.sortItems)): button = QPushButton(text) buttonLayout.addWidget(button) button.clicked.connect(slot) buttonLayout.addWidget(self.buttonBox) self.status = QLabel() layoutT.addLayout(layout) layoutT.addWidget(self.status) self.setLayout(layoutT) self.checklength() def add(self): self.status.setText('') lista = [] newitem = '' self.citytoadd = '' self.countrytoadd = '' self._idtoadd = '' dialog = searchcity.SearchCity(self.accurate_url, self.appid, self) dialog.id_signal.connect(self.addcity) dialog.city_signal.connect(self.addcity) dialog.country_signal.connect(self.addcity) if dialog.exec_() == 1: newitem = (self.citytoadd + '_' + self.countrytoadd + '_' + self._idtoadd) for row in range(self.listWidget.count()): lista.append(self.listWidget.item(row).text()) if newitem in lista: self.status.setText(QCoreApplication.translate( 'Status bar message', 'The city already exists in the list', 'Cities list dialogue')) return else: self.listWidget.addItem(newitem) self.checklength() def addcity(self, what): self.status.setText('') if what[0] == 'ID': self._idtoadd = what[1] elif what[0] == 'City': self.citytoadd = what[1] elif what[0] == 'Country': self.countrytoadd = what[1] def remove(self): self.status.setText('') if self.listWidget.count() == 0: self.status.setText(self.tr('The list is empty')) return row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is None: return message = self.tr('The city "{0}" has been removed').format( self.listWidget.item(row).text()) item = self.listWidget.takeItem(row) del item self.status.setText(message) def up(self): self.status.setText('') row = self.listWidget.currentRow() if row >= 1: item = self.listWidget.takeItem(row) self.listWidget.insertItem(row - 1, item) self.listWidget.setCurrentItem(item) def down(self): self.status.setText('') row = self.listWidget.currentRow() if row < self.listWidget.count() - 1: item = self.listWidget.takeItem(row) self.listWidget.insertItem(row + 1, item) self.listWidget.setCurrentItem(item) def default(self): self.status.setText('') row = self.listWidget.currentRow() if row >= 1: item = self.listWidget.takeItem(row) self.listWidget.insertItem(0, item) self.listWidget.setCurrentItem(item) def checklength(self): listtosend = [] for row in range(self.listWidget.count()): listtosend.append(self.listWidget.item(row).text()) if len(listtosend) == 0: return self.listWidget.setMinimumWidth(self.listWidget.sizeHintForColumn(0)) def accept(self): listtosend = [] for row in range(self.listWidget.count()): listtosend.append(self.listWidget.item(row).text()) self.citieslist_signal[list].emit(listtosend) QDialog.accept(self)
class SearchCity(QDialog): id_signal = pyqtSignal([tuple]) city_signal = pyqtSignal([tuple]) country_signal = pyqtSignal([tuple]) def __init__(self, accurate_url, appid, parent=None): super(SearchCity, self).__init__(parent) self.settings = QSettings() self.delay = 1000 self.search_string = self.tr('Searching...') self.timer = QTimer() self.accurate_url = accurate_url self.suffix = '&type=like&mode=xml' + appid self.layout = QVBoxLayout() self.lineLayout = QHBoxLayout() self.buttonSearch = QPushButton() self.buttonSearch.setIcon(QIcon(':/find')) self.buttonSearch.clicked.connect(self.search) self.line_search = QLineEdit(QCoreApplication.translate( 'Search city dialogue', 'Start typing the city...', '')) self.line_search.selectAll() self.listWidget = QListWidget() self.status = QLabel() self.lineLayout.addWidget(self.line_search) self.lineLayout.addWidget(self.buttonSearch) self.layout.addLayout(self.lineLayout) self.layout.addWidget(self.listWidget) self.layout.addWidget(self.status) self.buttonLayout = QHBoxLayout() self.buttonLayout.addStretch() self.buttonOk = QPushButton(self.tr('&Ok')) self.buttonOk.setEnabled(False) self.buttonCancel = QPushButton(self.tr('&Cancel')) self.buttonLayout.addWidget(self.buttonOk) self.buttonLayout.addWidget(self.buttonCancel) self.layout.addLayout(self.buttonLayout) self.setMinimumWidth(int(len(self.line_search.text())*20)) self.setLayout(self.layout) self.line_search.returnPressed.connect(self.search) self.line_search.textChanged.connect(self.timer_run) self.buttonOk.clicked.connect(self.accept) self.buttonCancel.clicked.connect(self.reject) self.listWidget.itemSelectionChanged.connect(self.buttonCheck) self.listWidget.itemDoubleClicked['QListWidgetItem *'].connect( self.accept) self.restoreGeometry(self.settings.value("SearchCity/Geometry", QByteArray())) self.timer_search = QTimer(self) self.timer_search.timeout.connect(self.search) def timer_run(self): self.timer_search.start(1000) def closeEvent(self, event): self.settings.setValue("SearchCity/Geometry", self.saveGeometry()) def moveEvent(self, event): self.settings.setValue("SearchCity/Geometry", self.saveGeometry()) def resizeEvent(self, event): self.settings.setValue("SearchCity/Geometry", self.saveGeometry()) def buttonCheck(self): '''Enable OK button if an item is selected''' row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is not None: self.buttonOk.setEnabled(True) def accept(self): row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is not None: selected_city = item.text() city_list = selected_city.split(' - ') for c in range(len(city_list)): city_list[c] = city_list[c].strip() id_ = 'ID', city_list[0] city = 'City', city_list[1] country = 'Country', city_list[2] self.id_signal[tuple].emit(id_) self.city_signal[tuple].emit(city) self.country_signal[tuple].emit(country) QDialog.accept(self) def thread_terminate(self): if hasattr(self, 'workThread'): if self.workThread.isRunning(): self.workThread.terminate() def search(self): self.timer_search.stop() self.city = (self.line_search.text()) self.thread_terminate() if len(self.city) < 3: self.status.setText(self.tr('Please type more than three letters')) return self.lista = [] self.errorStatus = False self.buttonOk.setEnabled(False) self.listWidget.clear() self.status.setText(self.search_string) self.workThread = WorkThread(self.accurate_url, self.city, self.suffix) self.workThread.setTerminationEnabled(True) self.workThread.city_signal['QString'].connect(self.addlist) self.workThread.finished.connect(self.result) self.workThread.error['QString'].connect(self.error) self.workThread.searching['QString'].connect(self.searching) self.workThread.started.connect(self.thread_started) self.timer.singleShot(self.delay, self.threadstart) def searching(self, message): '''Display a status message when searching takes a while''' self.status.setText(message) def thread_started(self): '''Force the "searching" status message''' self.status.setText(self.search_string) def threadstart(self): self.workThread.start() def addlist(self, city): logging.debug('Found: ' + str(city)) if city not in self.lista: self.lista.append(city) self.errorStatus = False def error(self, e): self.delay = 2000 logging.error(e) self.status.setText(e) self.adjustSize() self.errorStatus = True def result(self): if self.errorStatus: return if len(self.line_search.text()) < 3: self.thread_terminate() self.status.clear() return self.delay = 1000 # Clear the listWidget elements from an interrupted thread self.listWidget.clear() self.listWidget.addItems(self.lista) number_cities = len(self.lista) cities_text = '' if number_cities == 0: cities_text = self.tr('No results') elif number_cities == 1: cities_text = self.tr('Found {0} city').format(number_cities) elif number_cities > 1: cities_text = self.tr('Found {0} cities').format(number_cities) self.status.setText(cities_text)
class StringListDlg(QDialog): def __init__(self, name, stringlist=None, parent=None): super(StringListDlg, self).__init__(parent) self.name = name self.listWidget = QListWidget() if stringlist is not None: self.listWidget.addItems(stringlist) self.listWidget.setCurrentRow(0) buttonLayout = QVBoxLayout() for text, slot in (("&Add...", self.add), ("&Edit...", self.edit), ("&Remove...", self.remove), ("&Up", self.up), ("&Down", self.down), ("&Sort", self.listWidget.sortItems), ("Close", self.accept)): button = QPushButton(text) if not MAC: button.setFocusPolicy(Qt.NoFocus) if text == "Close": buttonLayout.addStretch() buttonLayout.addWidget(button) button.clicked.connect(slot) # self.connect(button, SIGNAL("clicked()"), slot) layout = QHBoxLayout() layout.addWidget(self.listWidget) layout.addLayout(buttonLayout) self.setLayout(layout) self.setWindowTitle("Edit {0} List".format(self.name)) def add(self): row = self.listWidget.currentRow() title = "Add {0}".format(self.name) string, ok = QInputDialog.getText(self, title, title) if ok and string is not None: self.listWidget.insertItem(row, string) def edit(self): row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is not None: title = "Edit {0}".format(self.name) string, ok = QInputDialog.getText(self, title, title, QLineEdit.Normal, item.text()) if ok and string is not None: item.setText(string) def remove(self): row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is None: return reply = QMessageBox.question(self, "Remove {0}".format( self.name), "Remove {0} `{1}'?".format( self.name, unicode(item.text())), QMessageBox.Yes|QMessageBox.No) if reply == QMessageBox.Yes: item = self.listWidget.takeItem(row) del item def up(self): row = self.listWidget.currentRow() if row >= 1: item = self.listWidget.takeItem(row) self.listWidget.insertItem(row - 1, item) self.listWidget.setCurrentItem(item) def down(self): row = self.listWidget.currentRow() if row < self.listWidget.count() - 1: item = self.listWidget.takeItem(row) self.listWidget.insertItem(row + 1, item) self.listWidget.setCurrentItem(item) def reject(self): self.accept() def accept(self): self.stringlist = QStringListModel().stringList() for row in range(self.listWidget.count()): self.stringlist.append(self.listWidget.item(row).text()) #self.stringlist.acceptedList.emit(self.stringlist) QDialog.accept(self)
class CityListDlg(QDialog): citieslist_signal = pyqtSignal([list]) citiesdict_signal = pyqtSignal([dict]) def __init__( self, citylist, accurate_url, appid, trans_cities_dict, parent=None ): super(CityListDlg, self).__init__(parent) self.settings = QSettings() self.citylist = citylist self.trans_cities_dict = trans_cities_dict self.accurate_url = accurate_url self.appid = appid self.listWidget = QListWidget() self.listWidget.itemDoubleClicked.connect(self.translate) cities_list = [] for i in self.citylist: cities_list.append(self.trans_cities_dict.get(i, i)) self.listWidget.addItems(cities_list) buttonLayout = QVBoxLayout() self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) self.buttonBox.rejected.connect(self.reject) self.buttonBox.accepted.connect(self.accept) layoutT = QVBoxLayout() layout = QHBoxLayout() layout.addWidget(self.listWidget) layout.addLayout(buttonLayout) for text, slot in ((self.tr("&Add..."), self.add), (self.tr("&Remove..."), self.remove), (self.tr("&Up"), self.up), (self.tr("&Down"), self.down), (self.tr("De&fault"), self.default), (self.tr("&Sort"), self.listWidget.sortItems)): button = QPushButton(text) buttonLayout.addWidget(button) button.clicked.connect(slot) self.translate_button = QPushButton( QCoreApplication.translate( 'Button', '&Translate', 'Edit cities name' ) ) buttonLayout.addWidget(self.translate_button) self.translate_button.clicked.connect(self.translate) buttonLayout.addWidget(self.buttonBox) self.status = QLabel() layoutT.addLayout(layout) layoutT.addWidget(self.status) self.setLayout(layoutT) self.setWindowTitle( QCoreApplication.translate( 'Window title', 'Cities', 'Cities list dialogue' ) ) self.checklength() def add(self): self.status.setText('') lista = [] newitem = '' self.citytoadd = '' self.countrytoadd = '' self._idtoadd = '' dialog = searchcity.SearchCity(self.accurate_url, self.appid, self) dialog.id_signal.connect(self.addcity) dialog.city_signal.connect(self.addcity) dialog.country_signal.connect(self.addcity) if dialog.exec_() == 1: newitem = ( self.citytoadd + '_' + self.countrytoadd + '_' + self._idtoadd ) for row in range(self.listWidget.count()): lista.append(self.listWidget.item(row).text()) if newitem in lista: self.status.setText( QCoreApplication.translate( 'Status bar message', 'The city already exists in the list', 'Cities list dialogue' ) ) return else: self.listWidget.addItem(newitem) self.checklength() self.status.setText( 'ℹ ' + QCoreApplication.translate( 'Status bar message', 'Toggle cities with mouse scroll on the weather window', 'Cities list dialogue' ) ) def addcity(self, what): self.status.setText('') if what[0] == 'ID': self._idtoadd = what[1] elif what[0] == 'City': self.citytoadd = what[1] elif what[0] == 'Country': self.countrytoadd = what[1] def remove(self): self.status.setText('') if self.listWidget.count() == 1: self.status.setText( QCoreApplication.translate( 'Message when trying to remove the' 'last and unique city in the list', 'This is the default city !', 'Cities list dialogue' ) ) return row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is None: return message = self.tr('The city "{0}" has been removed').format( self.listWidget.item(row).text()) item = self.listWidget.takeItem(row) del item self.status.setText(message) def up(self): self.status.setText('') row = self.listWidget.currentRow() if row >= 1: item = self.listWidget.takeItem(row) self.listWidget.insertItem(row - 1, item) self.listWidget.setCurrentItem(item) def down(self): self.status.setText('') row = self.listWidget.currentRow() if row < self.listWidget.count() - 1: item = self.listWidget.takeItem(row) self.listWidget.insertItem(row + 1, item) self.listWidget.setCurrentItem(item) def default(self): self.status.setText('') row = self.listWidget.currentRow() if row >= 1: item = self.listWidget.takeItem(row) self.listWidget.insertItem(0, item) self.listWidget.setCurrentItem(item) def checklength(self): if self.listWidget.count() == 1: # After adding the first city the entry is not activated self.listWidget.setCurrentRow(0) if self.listWidget.count() > 0: self.translate_button.setEnabled(True) self.listWidget.setMinimumWidth( self.listWidget.sizeHintForColumn(0) ) else: self.translate_button.setEnabled(False) def translate(self): city = self.listWidget.currentItem().text() dialog = citytranslate.CityTranslate( city, self.trans_cities_dict, self ) dialog.city_signal.connect(self.current_translation) if dialog.exec_() == 1: row = self.listWidget.currentRow() item = self.listWidget.takeItem(row) del item self.listWidget.insertItem(row, self.current_translated_city) self.listWidget.setCurrentRow(row) def current_translation(self, translated_city): for city, translated in translated_city.items(): if translated == '': translated = city self.trans_cities_dict[city] = translated self.current_translated_city = translated def accept(self): listtosend = [] for row in range(self.listWidget.count()): city = self.find_city_key(self.listWidget.item(row).text()) listtosend.append(city) if self.listWidget.count() == 0: return self.citieslist_signal[list].emit(listtosend) self.citiesdict_signal[dict].emit(self.trans_cities_dict) QDialog.accept(self) def find_city_key(self, city): for key, value in self.trans_cities_dict.items(): if value == city: return key return city
class QCWidget(QWidget): """QC Preferences Widget""" # Signals list2qc = pyqtSignal(list) def __init__(self): """Constructor""" super().__init__() self.initUI() def initUI(self): # Labels qcLabel = QLabel("QC procedures") resetLabel = QLabel("Reset QC: ") toLabel = QLabel("->") badRangeLabel = QLabel("- Bad QC: ") badFlatLabel = QLabel("- Bad QC: ") badSpikeLabel = QLabel("- Bad QC: ") rollingLabel = QLabel("Rolling window: ") thresholdLabel = QLabel("Threshold: ") parameterLabel = QLabel("Parameters: ") # Lists self.keyList = QListWidget(self) self.keyList.setEnabled(False) # Check Box self.resetCheck = QCheckBox("Reset QC", self) self.resetCheck.setChecked(True) self.rangeCheck = QCheckBox("Range test", self) self.rangeCheck.setChecked(True) self.flatCheck = QCheckBox("Flat test", self) self.flatCheck.setChecked(True) self.spikeCheck = QCheckBox("Spike test", self) self.spikeCheck.setChecked(True) self.flag2flagCheck = QCheckBox("Change flags", self) self.flag2flagCheck.setChecked(True) self.allCheck = QCheckBox("All", self) self.allCheck.setChecked(True) self.allCheck.toggled.connect(self.keyList.setDisabled) # Spin box self.originalSpinBox = QSpinBox(self) self.originalSpinBox.setMinimum(0) self.originalSpinBox.setMaximum(9) self.originalSpinBox.setValue(0) # - self.translatedSpinBox = QSpinBox(self) self.translatedSpinBox.setMinimum(0) self.translatedSpinBox.setMaximum(9) self.translatedSpinBox.setValue(1) # - self.badRangeSpinBox = QSpinBox(self) self.badRangeSpinBox.setMinimum(0) self.badRangeSpinBox.setMaximum(9) self.badRangeSpinBox.setMinimum(0) self.badRangeSpinBox.setValue(4) # - self.flatSpinBox = QSpinBox(self) self.flatSpinBox.setMinimum(0) self.flatSpinBox.setMaximum(9) self.flatSpinBox.setMinimum(0) self.flatSpinBox.setValue(4) # - self.spikeSpinBox = QSpinBox(self) self.spikeSpinBox.setMinimum(0) self.spikeSpinBox.setMaximum(9) self.spikeSpinBox.setMinimum(0) self.spikeSpinBox.setValue(4) # - self.rollingSpinBox = QSpinBox(self) self.rollingSpinBox.setValue(0) self.rollingSpinBox.setToolTip( "Size of the moving window.\n" "This is the number of observations used for calculating" " the mean.\n0 = Auto") # - self.resetSpinBox = QSpinBox(self) self.resetSpinBox.setMinimum(0) self.resetSpinBox.setMaximum(9) self.resetSpinBox.setMinimum(0) self.resetSpinBox.setValue(0) # - self.thresholdSpinBox = QDoubleSpinBox(self) self.thresholdSpinBox.setValue(2.00) self.thresholdSpinBox.setToolTip( "Maximum difference between the value analyzed and the average of" " the rooling window.") # Button applyButton = QPushButton("Apply") applyButton.clicked.connect(self.apply) closeButton = QPushButton("Hide") closeButton.clicked.connect(self.hide) # Layouts # - Horizontal Layout for reset hReset = QHBoxLayout() hReset.addWidget(resetLabel) hReset.addWidget(self.resetSpinBox) hReset.addStretch() # - Horizontal Layout for ranges hRanges = QHBoxLayout() hRanges.addWidget(badRangeLabel) hRanges.addWidget(self.badRangeSpinBox) hRanges.addStretch() # hRanges.addStretch() # - Horizontal Layout for flat hFlat = QHBoxLayout() hFlat.addWidget(badFlatLabel) hFlat.addWidget(self.flatSpinBox) hFlat.addStretch() # hFlat.addStretch() # - Horizontal Layout for spykes hSpykes = QHBoxLayout() hSpykes.addWidget(badSpikeLabel) hSpykes.addWidget(self.spikeSpinBox) hSpykes.addStretch() # - Horizontal Layout for threshold hThreshold = QHBoxLayout() hThreshold.addWidget(thresholdLabel) hThreshold.addWidget(self.thresholdSpinBox) hThreshold.addStretch() # - Horizontal Layout for rolling window hRolling = QHBoxLayout() hRolling.addWidget(rollingLabel) hRolling.addWidget(self.rollingSpinBox) hRolling.addStretch() # - Horizontal Layout for flag2flag - hFlag2flag = QHBoxLayout() hFlag2flag.addWidget(self.originalSpinBox) hFlag2flag.addWidget(toLabel) hFlag2flag.addWidget(self.translatedSpinBox) hFlag2flag.addStretch() # - Vertical Layout for the Widget vQC = QVBoxLayout() vQC.addWidget(parameterLabel) vQC.addWidget(self.allCheck) vQC.addWidget(self.keyList) vQC.addWidget(qcLabel) vQC.addWidget(self.resetCheck) vQC.addLayout(hReset) vQC.addWidget(self.rangeCheck) vQC.addLayout(hRanges) vQC.addWidget(self.flatCheck) vQC.addLayout(hFlat) vQC.addWidget(self.spikeCheck) vQC.addLayout(hSpykes) vQC.addLayout(hThreshold) vQC.addLayout(hRolling) vQC.addWidget(self.flag2flagCheck) vQC.addLayout(hFlag2flag) vQC.addWidget(applyButton) vQC.addWidget(closeButton) vQC.addStretch() self.setLayout(vQC) def apply(self): """ Emit a signal with the current QC settings """ settings = [] if self.resetCheck.isChecked(): settings.append(self.resetSpinBox.text()) else: settings.append(None) if self.rangeCheck.isChecked(): settings.append(self.badRangeSpinBox.text()) else: settings.append(None) if self.flatCheck.isChecked(): settings.append(self.flatSpinBox.text()) else: settings.append(None) if self.spikeCheck.isChecked(): settings.append(self.spikeSpinBox.text()) else: settings.append(None) settings.append(self.thresholdSpinBox.text()) settings.append(self.rollingSpinBox.text()) if self.flag2flagCheck.isChecked(): settings.append(self.originalSpinBox.text()) settings.append(self.translatedSpinBox.text()) else: settings.append(None) settings.append(None) if self.allCheck.isChecked(): settings.append("all") else: for index in range(self.keyList.count()): item = self.keyList.item(index) if item.checkState(): settings.append(item.text()) self.list2qc.emit(settings) def addLabels(self, labels): """ Add items to self.dropList """ # Clear the list self.keyList.clear() # Add new items self.keyList.addItems(labels) # Configure the items checkable for index in range(self.keyList.count()): item = self.keyList.item(index) item.setFlags(item.flags() | Qt.ItemIsUserCheckable) item.setCheckState(Qt.Unchecked)
class Window(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.lineinp = QLineEdit(self) self.lineinp.setPlaceholderText("Enter the site's URL here") self.boxinp = QComboBox(self) self.boxinp.addItems(['LiveLib', 'ReadRate', 'Libs', 'Readly']) self.prsbtn = QPushButton('Parse!', self) self.prsbtn.clicked.connect(self.prsbuttonClicked) self.wtfbtn = QPushButton('WTF', self) self.wtfbtn.clicked.connect(self.wtfbuttonClicked) self.datalist = QListWidget(self) self.msgbox = QMessageBox() self.msgbtn = QPushButton('Попробовать снова') self.msgbox.addButton(self.msgbtn, QMessageBox.DestructiveRole) self.msgbox.setWindowTitle('Ой, что-то не так') self.msgbox.setWindowIcon(QIcon('sad.png')) self.center(self.msgbox) grid = QGridLayout() grid.addWidget(self.lineinp, 1, 0, 1, 2) grid.addWidget(self.boxinp, 2, 0, 1, 2) grid.addWidget(self.prsbtn, 3, 0) grid.addWidget(self.wtfbtn, 3, 1) grid.addWidget(self.datalist, 4, 0, 4, 2) self.setLayout(grid) self.boxinp.hide() self.resize(600, 600) self.center(self) self.setWindowTitle('My big fully-functional parser') self.setWindowIcon(QIcon('www.png')) self.show() def center(self, obj): qr = obj.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def wtfbuttonClicked(self): if self.boxinp.isVisible(): self.boxinp.hide() self.lineinp.show() else: self.boxinp.show() self.lineinp.hide() def prsbuttonClicked(self): self.datalist.clear() if self.lineinp.isVisible(): self.setTopByLine() else: self.setTopByBox() def connection_try(self, currentsite): try: data = currentsite.get_books_list() except requests.exceptions.ConnectionError: self.msgbox.setText('Ошибка сети') self.msgbox.setInformativeText('Проверьте подключение к интернету') self.msgbox.show() else: self.datalist.addItems(data) def setTopByBox(self): sitename = self.boxinp.currentText() currentsite = backend.sites[sitename] self.connection_try(currentsite) # На самом деле очевидно, что данный парсер с его архитектурой # весьма глупо реализовывать через ввод URL # данная возможность предусмотренна исключетельно ради примера использования QLineEdit def setTopByLine(self): siteurl = self.lineinp.text() if siteurl in backend.urls: currentsite = backend.urls[siteurl] self.connection_try(currentsite) else: self.msgbox.setText('Что такое?') self.msgbox.setInformativeText('Введите нормальный URL') self.msgbtn.clicked.connect(lambda: self.prsbtn.setText('Исправил, проверяйте')) self.msgbox.show()
class Theme(QWidget): """Theme widget class.""" def __init__(self, parent): super(Theme, self).__init__() self._preferences, vbox = parent, QVBoxLayout(self) vbox.addWidget(QLabel(self.tr("<b>Select Theme:</b>"))) self.list_skins = QListWidget() self.list_skins.setSelectionMode(QListWidget.SingleSelection) vbox.addWidget(self.list_skins) self.btn_delete = QPushButton(self.tr("Delete Theme")) self.btn_preview = QPushButton(self.tr("Preview Theme")) self.btn_create = QPushButton(self.tr("Create Theme")) hbox = QHBoxLayout() hbox.addWidget(self.btn_delete) hbox.addSpacerItem(QSpacerItem(10, 0, QSizePolicy.Expanding, QSizePolicy.Fixed)) hbox.addWidget(self.btn_preview) hbox.addWidget(self.btn_create) vbox.addLayout(hbox) self._refresh_list() self.btn_preview.clicked['bool'].connect(self.preview_theme) self.btn_delete.clicked['bool'].connect(self.delete_theme) self.btn_create.clicked['bool'].connect(self.create_theme) self._preferences.savePreferences.connect(self.save) def delete_theme(self): if self.list_skins.currentRow() != 0: file_name = ("%s.qss" % self.list_skins.currentItem().text()) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) file_manager.delete_file(qss_file) self._refresh_list() def create_theme(self): designer = preferences_theme_editor.ThemeEditor(self) designer.exec_() self._refresh_list() def showEvent(self, event): self._refresh_list() super(Theme, self).showEvent(event) def _refresh_list(self): self.list_skins.clear() self.list_skins.addItem("Default") files = [file_manager.get_file_name(filename) for filename in file_manager.get_files_from_folder( resources.NINJA_THEME_DOWNLOAD, "qss")] files.sort() self.list_skins.addItems(files) if settings.NINJA_SKIN in files: index = files.index(settings.NINJA_SKIN) self.list_skins.setCurrentRow(index + 1) else: self.list_skins.setCurrentRow(0) def save(self): qsettings = IDE.ninja_settings() settings.NINJA_SKIN = self.list_skins.currentItem().text() qsettings.setValue("preferences/theme/skin", settings.NINJA_SKIN) self.preview_theme() def preview_theme(self): if self.list_skins.currentRow() == 0: qss_file = resources.NINJA_THEME else: file_name = ("%s.qss" % self.list_skins.currentItem().text()) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) with open(qss_file) as f: qss = f.read() QApplication.instance().setStyleSheet(qss)
class Example(QWidget): def __init__(self, parent=None): super(Example, self).__init__(parent) QApplication.setStyle(QStyleFactory.create('Fusion')) # -------------- QCOMBOBOX ---------------------- cbx = QComboBox() # agregar lista de nombres de estilos disponibles cbx.addItems(QStyleFactory.keys()) # responder al evento cambio de texto cbx.currentTextChanged.connect(self.textChanged) # seleccionar el ultimo elemento cbx.setItemText(4, 'Fusion') # -------------- QLISTWIDGET --------------------- items = ['Ubuntu', 'Linux', 'Mac OS', 'Windows', 'Fedora', 'Chrome OS', 'Android', 'Windows Phone'] self.lv = QListWidget() self.lv.addItems(items) self.lv.itemSelectionChanged.connect(self.itemChanged) # -------------- QTABLEWIDGET -------------------- self.table = QTableWidget(10, 3) # establecer nombre de cabecera de las columnas self.table.setHorizontalHeaderLabels(['Nombre', 'Edad', 'Nacionalidad']) # evento producido cuando cambia el elemento seleccionado self.table.itemSelectionChanged.connect(self.tableItemChanged) # alternar color de fila self.table.setAlternatingRowColors(True) # seleccionar solo filas self.table.setSelectionBehavior(QTableWidget.SelectRows) # usar seleccion simple, una fila a la vez self.table.setSelectionMode(QTableWidget.SingleSelection) table_data = [ ("Alice", 15, "Panama"), ("Dana", 25, "Chile"), ("Fernada", 18, "Ecuador") ] # agregar cada uno de los elementos al QTableWidget for i, (name, age, city) in enumerate(table_data): self.table.setItem(i, 0, QTableWidgetItem(name)) self.table.setItem(i, 1, QTableWidgetItem(str(age))) self.table.setItem(i, 2, QTableWidgetItem(city)) vbx = QVBoxLayout() vbx.addWidget(QPushButton('Tutoriales PyQT-5')) vbx.setAlignment(Qt.AlignTop) vbx.addWidget(cbx) vbx.addWidget(self.lv) vbx.addWidget(self.table) self.setWindowTitle("Items View") self.resize(362, 320) self.setLayout(vbx) def textChanged(self, txt): QApplication.setStyle(QStyleFactory.create(txt)) def itemChanged(self): item = QListWidgetItem(self.lv.currentItem()) print("Sistema seleccionado: ", item.text()) def tableItemChanged(self): name, age, city = self.table.selectedItems() print("Data:", name.text(), age.text(), city.text())
class UriChangerDialog(QDialog): def __init__(self, **kwargs): super().__init__(**kwargs) self.resize(600, 300) self.setLayout(QVBoxLayout()) # FILE SELECT self.sessionLayout = QHBoxLayout() self.layout().addLayout(self.sessionLayout) self.sessionFileEdit = QLineEdit(self) self.sessionFileEdit.editingFinished.connect(self.session_init) self.sessionLayout.addWidget(self.sessionFileEdit) self.sessionFileSelect = QPushButton(self) self.sessionFileSelect.clicked.connect(self.session_select) self.sessionLayout.addWidget(self.sessionFileSelect) self.sessionReload = QPushButton(self) self.sessionReload.setIcon(QIcon.fromTheme('view-refresh')) self.sessionReload.clicked.connect(self.session_init) self.sessionLayout.addWidget(self.sessionReload) # REPLACE self.replaceLayout = QGridLayout() self.layout().addLayout(self.replaceLayout) self.currentLabel = QLabel(self) self.currentLabel.setAlignment(Qt.AlignCenter) self.replaceLayout.addWidget(self.currentLabel, 0, 0) self.replaceLabel = QLabel(self) self.replaceLabel.setAlignment(Qt.AlignCenter) self.replaceLayout.addWidget(self.replaceLabel, 0, 1) self.prefixList = QListWidget(self) self.prefixList.currentTextChanged.connect(self.prefix_changed) self.replaceLayout.addWidget(self.prefixList, 1, 0, 2, 1) self.newPrefixLayout = QVBoxLayout() self.replaceLayout.addLayout(self.newPrefixLayout, 1, 1) self.prefixEdit = QLineEdit(self) self.newPrefixLayout.addWidget(self.prefixEdit) self.replaceLayout.setAlignment(self.prefixEdit, Qt.AlignTop) self.replaceApply = QPushButton(self) self.replaceApply.clicked.connect(self.session_replace) self.newPrefixLayout.addWidget(self.replaceApply) self.newPrefixLayout.setAlignment(self.replaceApply, Qt.AlignRight) self.buttons = QDialogButtonBox(self) self.buttons.setStandardButtons(QDialogButtonBox.Cancel) self.buttons.rejected.connect(self.reject) self.layout().addWidget(self.buttons) self.saveButton = self.buttons.addButton(QDialogButtonBox.Save) self.saveButton.clicked.connect(self.session_save) self.retranslateUi() self.session = None def retranslateUi(self): self.currentLabel.setText(translate('UriChanger', 'Current')) self.replaceLabel.setText(translate('UriChanger', 'Replace')) self.sessionFileSelect.setText(translate('UriChanger', 'Session file')) self.sessionReload.setToolTip(translate('UriChanger', 'Reload')) self.replaceApply.setText(translate('UriChanger', 'Replace')) def prefix_changed(self, prefix): if self.prefixEdit.text() == '': self.prefixEdit.setText(prefix) else: # Search if the prefixEdit text is one of the listed prefixes lower = 0 upper = self.prefixList.count() - 1 search = self.prefixEdit.text() while lower <= upper: middle = (lower + upper) // 2 item = self.prefixList.item(middle).text() if item < search: lower = middle + 1 elif item > search: upper = middle - 1 else: self.prefixEdit.setText(prefix) break def session_select(self): file, _ = QFileDialog.getOpenFileName(self, filter='*.lsp', directory=os.getenv('HOME')) if file != '': self.sessionFileEdit.setText(file) self.session_init() def session_analyze(self): self.prefixList.clear() self.prefixList.addItems(self.session.analyze()) self.prefixList.sortItems() def session_init(self): file = self.sessionFileEdit.text() if os.path.exists(file): self.session = Session(file) self.session_analyze() elif file.strip() != '': QMessageBox.critical( self, translate('UriChanger', 'Error'), translate('UriChanger', 'Session file "{}" not found'.format(file))) def session_replace(self): self.session.replace(self.prefixList.currentItem().text(), self.prefixEdit.text()) self.session_analyze() def session_save(self): file, ok = QFileDialog.getSaveFileName(self, filter='*.lsp', directory=os.getenv('HOME')) if ok: self.session.save(file) self.accept()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.createActions() self.createMenus() self.createStatusBar() self.createDockWindows() self.setWindowTitle("Deploy Simulator") def about(self): QMessageBox.about(self, "About DeploySimulator", "The <b>DeploySimulator</b> uses to simulate the environment " "of wireless sendor networks, with numberous sensors.") def changeEnvironment(self, environment): if not environment: return environmentList = environment.split(', ') for i in environmentList[:]: print("changeEnvironment-->"+i) def createActions(self): self.exitAct = QAction("E&xit", self, shortcut="Ctrl+Q", statusTip="Exit the application", triggered=self.close) self.aboutAct = QAction("&About", self, statusTip="Show the application's About box", triggered=self.about) self.aboutQtAct = QAction("About &Qt", self, statusTip="Show the Qt library's About box", triggered=QApplication.instance().aboutQt) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addSeparator(); self.fileMenu.addAction(self.exitAct) self.viewMenu = self.menuBar().addMenu("&View") self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) def createStatusBar(self): self.statusBar().showMessage("Ready") def createDockWindows(self): dock = QDockWidget("Sensors", self) dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.sensors= Sensors(dock) dock.setWidget(self.sensors) self.addDockWidget(Qt.RightDockWidgetArea, dock) self.viewMenu.addAction(dock.toggleViewAction()) dock = QDockWidget("Environment", self) dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.environmentList = QListWidget(dock) self.environmentList.addItems(( "Omnidirectional Sensor Networks", "Directional Sensor Networks", "Directional Path Tracking", "Big Target Coverage")) dock.setWidget(self.environmentList) self.addDockWidget(Qt.RightDockWidgetArea, dock) self.viewMenu.addAction(dock.toggleViewAction()) dock = QDockWidget("Simulation", self) dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.simulation= Simulation(dock) dock.setWidget(self.simulation) self.addDockWidget(Qt.LeftDockWidgetArea, dock) self.viewMenu.addAction(dock.toggleViewAction()) dock = QDockWidget("Console", self) dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.console= Console(dock) dock.setWidget(self.console) self.addDockWidget(Qt.LeftDockWidgetArea, dock) self.viewMenu.addAction(dock.toggleViewAction()) self.console.applyButton.clicked.connect(self.applyButtonState) self.console.playButton.clicked.connect(self.playButtonState) self.console.pauseButton.clicked.connect(self.pauseButtonState) self.environmentList.currentTextChanged.connect(self.changeEnvironment) def applyButtonState(self): if self.console.applyButton.isChecked(): pass else: self.simulation.initialization(float(self.sensors.radDownText1.text()), float(self.sensors.radUpText1.text()), int(self.sensors.angDownText.text()), int(self.sensors.angUpText.text()), int(self.sensors.numText1.text()), float(self.sensors.radDownText2.text()), float(self.sensors.radUpText2.text()), int(self.sensors.numText2.text())) def playButtonState(self): if self.console.playButton.isChecked(): pass else: self.simulation.setAnimating(True) print('play button clicked') def pauseButtonState(self): if self.console.pauseButton.isChecked(): pass else: self.simulation.setAnimating(False) print('pause button clicked') def adjustButtonState(self): if self.console.adjustButton.isChecked(): pass else: self.simulation.setTime(float(self.console.speedSpin.text()))
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.textEdit = QTextEdit() self.setCentralWidget(self.textEdit) self.createActions() self.createMenus() self.createToolBars() self.createStatusBar() self.createDockWindows() self.setWindowTitle("Dock Widgets") self.newLetter() def newLetter(self): self.textEdit.clear() cursor = self.textEdit.textCursor() cursor.movePosition(QTextCursor.Start) topFrame = cursor.currentFrame() topFrameFormat = topFrame.frameFormat() topFrameFormat.setPadding(16) topFrame.setFrameFormat(topFrameFormat) textFormat = QTextCharFormat() boldFormat = QTextCharFormat() boldFormat.setFontWeight(QFont.Bold) italicFormat = QTextCharFormat() italicFormat.setFontItalic(True) tableFormat = QTextTableFormat() tableFormat.setBorder(1) tableFormat.setCellPadding(16) tableFormat.setAlignment(Qt.AlignRight) cursor.insertTable(1, 1, tableFormat) cursor.insertText("The Firm", boldFormat) cursor.insertBlock() cursor.insertText("321 City Street", textFormat) cursor.insertBlock() cursor.insertText("Industry Park") cursor.insertBlock() cursor.insertText("Some Country") cursor.setPosition(topFrame.lastPosition()) cursor.insertText(QDate.currentDate().toString("d MMMM yyyy"), textFormat) cursor.insertBlock() cursor.insertBlock() cursor.insertText("Dear ", textFormat) cursor.insertText("NAME", italicFormat) cursor.insertText(",", textFormat) for i in range(3): cursor.insertBlock() cursor.insertText("Yours sincerely,", textFormat) for i in range(3): cursor.insertBlock() cursor.insertText("The Boss", textFormat) cursor.insertBlock() cursor.insertText("ADDRESS", italicFormat) def print_(self): document = self.textEdit.document() printer = QPrinter() dlg = QPrintDialog(printer, self) if dlg.exec_() != QDialog.Accepted: return document.print_(printer) self.statusBar().showMessage("Ready", 2000) def save(self): filename, _ = QFileDialog.getSaveFileName(self, "Choose a file name", ".", "HTML (*.html *.htm)") if not filename: return file = QFile(filename) if not file.open(QFile.WriteOnly | QFile.Text): QMessageBox.warning( self, "Dock Widgets", "Cannot write file %s:\n%s." % (filename, file.errorString()), ) return out = QTextStream(file) QApplication.setOverrideCursor(Qt.WaitCursor) out << self.textEdit.toHtml() QApplication.restoreOverrideCursor() self.statusBar().showMessage("Saved '%s'" % filename, 2000) def undo(self): document = self.textEdit.document() document.undo() def insertCustomer(self, customer): if not customer: return customerList = customer.split(", ") document = self.textEdit.document() cursor = document.find("NAME") if not cursor.isNull(): cursor.beginEditBlock() cursor.insertText(customerList[0]) oldcursor = cursor cursor = document.find("ADDRESS") if not cursor.isNull(): for i in customerList[1:]: cursor.insertBlock() cursor.insertText(i) cursor.endEditBlock() else: oldcursor.endEditBlock() def addParagraph(self, paragraph): if not paragraph: return document = self.textEdit.document() cursor = document.find("Yours sincerely,") if cursor.isNull(): return cursor.beginEditBlock() cursor.movePosition(QTextCursor.PreviousBlock, QTextCursor.MoveAnchor, 2) cursor.insertBlock() cursor.insertText(paragraph) cursor.insertBlock() cursor.endEditBlock() def about(self): QMessageBox.about( self, "About Dock Widgets", "The <b>Dock Widgets</b> example demonstrates how to use " "Qt's dock widgets. You can enter your own text, click a " "customer to add a customer name and address, and click " "standard paragraphs to add them.", ) def createActions(self): self.newLetterAct = QAction( QIcon(":/images/new.png"), "&New Letter", self, shortcut=QKeySequence.New, statusTip="Create a new form letter", triggered=self.newLetter, ) self.saveAct = QAction( QIcon(":/images/save.png"), "&Save...", self, shortcut=QKeySequence.Save, statusTip="Save the current form letter", triggered=self.save, ) self.printAct = QAction( QIcon(":/images/print.png"), "&Print...", self, shortcut=QKeySequence.Print, statusTip="Print the current form letter", triggered=self.print_, ) self.undoAct = QAction( QIcon(":/images/undo.png"), "&Undo", self, shortcut=QKeySequence.Undo, statusTip="Undo the last editing action", triggered=self.undo, ) self.quitAct = QAction( "&Quit", self, shortcut="Ctrl+Q", statusTip="Quit the application", triggered=self.close, ) self.aboutAct = QAction( "&About", self, statusTip="Show the application's About box", triggered=self.about, ) self.aboutQtAct = QAction( "About &Qt", self, statusTip="Show the Qt library's About box", triggered=QApplication.instance().aboutQt, ) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newLetterAct) self.fileMenu.addAction(self.saveAct) self.fileMenu.addAction(self.printAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.quitAct) self.editMenu = self.menuBar().addMenu("&Edit") self.editMenu.addAction(self.undoAct) self.viewMenu = self.menuBar().addMenu("&View") self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) def createToolBars(self): self.fileToolBar = self.addToolBar("File") self.fileToolBar.addAction(self.newLetterAct) self.fileToolBar.addAction(self.saveAct) self.fileToolBar.addAction(self.printAct) self.editToolBar = self.addToolBar("Edit") self.editToolBar.addAction(self.undoAct) def createStatusBar(self): self.statusBar().showMessage("Ready") def createDockWindows(self): dock = QDockWidget("Customers", self) dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.customerList = QListWidget(dock) self.customerList.addItems(( "John Doe, Harmony Enterprises, 12 Lakeside, Ambleton", "Jane Doe, Memorabilia, 23 Watersedge, Beaton", "Tammy Shea, Tiblanka, 38 Sea Views, Carlton", "Tim Sheen, Caraba Gifts, 48 Ocean Way, Deal", "Sol Harvey, Chicos Coffee, 53 New Springs, Eccleston", "Sally Hobart, Tiroli Tea, 67 Long River, Fedula", )) dock.setWidget(self.customerList) self.addDockWidget(Qt.RightDockWidgetArea, dock) self.viewMenu.addAction(dock.toggleViewAction()) dock = QDockWidget("Paragraphs", self) self.paragraphsList = QListWidget(dock) self.paragraphsList.addItems(( "Thank you for your payment which we have received today.", "Your order has been dispatched and should be with you within " "28 days.", "We have dispatched those items that were in stock. The rest of " "your order will be dispatched once all the remaining items " "have arrived at our warehouse. No additional shipping " "charges will be made.", "You made a small overpayment (less than $5) which we will keep " "on account for you, or return at your request.", "You made a small underpayment (less than $1), but we have sent " "your order anyway. We'll add this underpayment to your next " "bill.", "Unfortunately you did not send enough money. Please remit an " "additional $. Your order will be dispatched as soon as the " "complete amount has been received.", "You made an overpayment (more than $5). Do you wish to buy more " "items, or should we return the excess to you?", )) dock.setWidget(self.paragraphsList) self.addDockWidget(Qt.RightDockWidgetArea, dock) self.viewMenu.addAction(dock.toggleViewAction()) self.customerList.currentTextChanged.connect(self.insertCustomer) self.paragraphsList.currentTextChanged.connect(self.addParagraph)
class ApplicationWindow(QMainWindow): def __init__(self): self.list_file_names = list() self.list_data = list() self.current_data = 0 self.selected_datas = 0 QMainWindow.__init__(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle("application main window") self.file_menu = QMenu('&File', self) self.file_menu.addAction('&Quit', self.fileQuit, QtCore.Qt.CTRL + QtCore.Qt.Key_Q) self.menuBar().addMenu(self.file_menu) self.help_menu = QMenu('&Help', self) self.menuBar().addSeparator() self.menuBar().addMenu(self.help_menu) self.help_menu.addAction('&About', self.about) open_file_action = QAction(QIcon('openfileicon.png'), 'OPEN', self) open_file_action.setShortcut('Ctrl+O') open_file_action.triggered.connect(self.openFiles) self.toolbar = self.addToolBar('Exit') self.toolbar.addAction(open_file_action) self.list_widjet_file_names = QListWidget() self.list_widjet_file_names.setSelectionMode(QAbstractItemView.ExtendedSelection) self.list_widjet_file_names.itemDoubleClicked.connect(self.draw_choose_plot) self.draw_button = QPushButton() self.draw_button.clicked.connect(self.drawSelected) self.ipython_widget = mywg.jup_widget() started = self.ipython_widget._started_kernel() print(started) spin_multiply = QSpinBox(self) spin_multiply.setRange(1, 1000) spin_multiply.setValue(1) spin_multiply.resize(300, 50) self.label = QLabel(self) self.label.setText("1") self.main_widget = QWidget(self) # all layouts main_layout = QHBoxLayout() left_layout = QVBoxLayout() center_layout = QVBoxLayout() right_layout = QVBoxLayout() list_file_names_layout = QVBoxLayout() # combine Layouts main_layout.addLayout(left_layout) main_layout.addLayout(center_layout) main_layout.addLayout(right_layout) left_layout.addLayout(list_file_names_layout) self.setLayout(main_layout) self.data = 0 self.sc = my_widgets.MyMainCanvas(self, width=5, height=4, dpi=100) spin_multiply.valueChanged[int].connect(self.multy_data) # dc = MyDynamicMplCanvas(self.main_widget, width=5, height=4, dpi=100) # add widjets to layouts left_layout.addWidget(spin_multiply) # right_layout.addWidget(spin2) center_layout.addWidget(self.sc) list_file_names_layout.addWidget(self.list_widjet_file_names) list_file_names_layout.addWidget(self.draw_button) right_layout.addWidget(self.ipython_widget) self.main_widget.setLayout(main_layout) self.main_widget.setFocus() self.ipython_widget._show_interpreter_prompt(0) print("bumbum") self.setCentralWidget(self.main_widget) self.statusBar().showMessage("All hail matplotlib!", 2000) def fileQuit(self): self.close() def drawSelected(self): datas = self.list_widjet_file_names.selectedItems() print(datas[0]) def openFiles(self): file_names = QFileDialog.getOpenFileNames(self, "D:\\Programming\\Job\\Laba\\Laba\\Preprocess\\DataFiles\\") newlist = list(file_names) new_file_names = list(newlist[0]) need_file_names = list() new_data_list = list() for fname in new_file_names: if fname not in self.list_file_names: need_file_names.append(str(fname)) for fname in need_file_names: newdata = dl.load_file(fname) new_data_list.append(newdata) self.list_data += new_data_list self.list_file_names += need_file_names self.list_widjet_file_names.addItems(need_file_names) def draw_choose_plot(self, filename): index = self.list_file_names.index(filename.text()) self.current_data = self.list_data[index] self.sc.update_figure(self.current_data.dataXY[:, 0], self.current_data.dataXY[:, 1]) def multy_data(self, val): if self.current_data == 0: print(2) return 0 self.sc.update_figure(self.current_data.dataXY[:, 0], self.current_data.dataXY[:, 1]*val) def closeEvent(self, ce): self.fileQuit() def update_label(self, val): self.label.setText(val) def about(self): QMessageBox.about(self, "About", """embedding_in_qt5.py example Copyright 2015 BoxControL This program is a simple example of a Qt5 application embedding matplotlib canvases. It is base on example from matplolib documentation, and initially was developed from Florent Rougon and Darren Dale. http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html It may be used and modified with no restriction; raw copies as well as modified versions may be distributed without limitation.""" )
class Lookup(QWidget): MODEL_CLASS = None def __init__(self, parent, model): QWidget.__init__(self, parent, Qt.Window) self.model = model self.model.view = self self._setupUi() self.searchEdit.searchChanged.connect(self.searchChanged) self.searchEdit.returnPressed.connect(self.returnPressed) self.namesList.currentRowChanged.connect(self.currentRowChanged) self.namesList.itemDoubleClicked.connect(self.itemDoubleClicked) self._shortcutUp.activated.connect(self.upPressed) self._shortcutDown.activated.connect(self.downPressed) def _setupUi(self): self.setWindowTitle(tr("Lookup")) self.resize(314, 331) self.verticalLayout = QVBoxLayout(self) self.searchEdit = SearchEdit(self) self.verticalLayout.addWidget(self.searchEdit) self.namesList = QListWidget(self) self.namesList.setEditTriggers(QAbstractItemView.NoEditTriggers) self.namesList.setSelectionBehavior(QAbstractItemView.SelectRows) self.namesList.setUniformItemSizes(True) self.namesList.setSelectionRectVisible(True) self.verticalLayout.addWidget(self.namesList) self.searchEdit.immediate = True self._shortcutUp = QShortcut(self.searchEdit) self._shortcutUp.setKey(QKeySequence(Qt.Key_Up)) self._shortcutUp.setContext(Qt.WidgetShortcut) self._shortcutDown = QShortcut(self.searchEdit) self._shortcutDown.setKey(QKeySequence(Qt.Key_Down)) self._shortcutDown.setContext(Qt.WidgetShortcut) def _restoreSelection(self): self.namesList.setCurrentRow(self.model.selected_index) # --- Event Handlers def returnPressed(self): self.model.go() def searchChanged(self): self.model.search_query = str(self.searchEdit.text()) def currentRowChanged(self, row): if row >= 0: self.model.selected_index = row def itemDoubleClicked(self, item): self.model.go() def upPressed(self): if self.namesList.currentRow() > 0: self.namesList.setCurrentRow(self.namesList.currentRow() - 1) def downPressed(self): if self.namesList.currentRow() < self.namesList.count() - 1: self.namesList.setCurrentRow(self.namesList.currentRow() + 1) # --- model --> view def refresh(self): self.namesList.clear() self.namesList.addItems(self.model.names) self._restoreSelection() self.searchEdit.setText(self.model.search_query) def show(self): QWidget.show(self) self.searchEdit.setFocus() # see csv_options self.raise_() def hide(self): QWidget.hide(self)
class H5PlotGUI(QDialog): """The main GUI for H5Plot. From here the SolSets, SolTabs and antennas to plot are selected. """ def __init__(self, h5file, logging_instance, parent=None): super(H5PlotGUI, self).__init__(parent) self.logger = logging_instance self.figures = [] self.h5parm = lh5.h5parm(h5file) self.solset_labels = self.h5parm.getSolsetNames() self.solset = self.h5parm.getSolset('sol000') self.soltab_labels = self.solset.getSoltabNames() self.soltab = self.solset.getSoltab(self.soltab_labels[0]) self.stations = self.soltab.getValues()[1]['ant'] self.refant = 'CS001HBA0' self.wrapphase = True self.stcache = SoltabCache(self.soltab.getValues(), self.soltab.getAxesNames()) rvals, raxes = reorder_soltab(self.soltab) self.stcache.update(rvals, raxes) self.move(300, 300) self.setWindowTitle('H5Plot') self.solset_label = QLabel('SolSet: ') self.solset_picker = QComboBox() for l in self.solset_labels: self.solset_picker.addItem(l) self.solset_picker.activated.connect(self._solset_picker_event) self.soltab_label_y = QLabel('Plot ') self.soltab_label_x = QLabel(' vs ') self.soltab_picker = QComboBox() for l in self.soltab_labels: self.soltab_picker.addItem(l) self.soltab_picker.activated.connect(self._soltab_picker_event) self.axis_picker = QComboBox() self.axis_picker.addItems(['time', 'freq']) self.axis_picker.activated.connect(self._axis_picker_event) self.axis = 'time' self.refant_label = QLabel('Ref. Ant. ') self.refant_picker = QComboBox() self.refant_picker.addItems(self.stations) self.refant_picker.activated.connect(self._refant_picker_event) self.phasewrap_box = QCheckBox('Wrap Phases') self.phasewrap_box.setChecked(True) self.phasewrap_box.setEnabled(False) self.phasewrap_box.stateChanged.connect(self._phasewrap_event) self.plot_button = QPushButton('Plot') self.plot_button.clicked.connect(self._plot_button_event) self.station_picker = QListWidget() self.station_picker.addItems(self.stations) self.station_picker.setCurrentRow(0) plot_layout = QGridLayout() plot_layout.addWidget(self.soltab_label_y, 0, 0) plot_layout.addWidget(self.soltab_picker, 0, 1) plot_layout.addWidget(self.soltab_label_x, 0, 2) plot_layout.addWidget(self.axis_picker, 0, 3) plot_layout.addWidget(self.refant_label, 1, 0) plot_layout.addWidget(self.refant_picker, 1, 1) plot_layout.addWidget(self.phasewrap_box, 1, 3) layout = QFormLayout(self) layout.addRow(self.solset_label, self.solset_picker) layout.addRow(plot_layout) layout.addRow(self.plot_button) layout.addRow(self.station_picker) def _axis_picker_event(self): """Callback function for when the x-axis is changed. Sets the `axis` attribute to the selected axis """ self.logger.debug('Axis changed to: ' + self.axis_picker.currentText()) self.axis = self.axis_picker.currentText() def closeEvent(self, event): self.logger.info('Closing all open figures before exiting.') plt.close('all' ) event.accept() def _refant_picker_event(self): self.logger.debug('Reference antenna changed to: ' + self.refant_picker.currentText()) self.refant = self.refant_picker.currentText() def _solset_picker_event(self): """Callback function for when the SolSet is changed. Sets the `solset` attribute. """ self.logger.debug('Solset changed to: ' + self.solset_picker.currentText()) self.solset = self.h5parm.getSolset(self.solset_picker.currentText()) self.soltab_labels = self.solset.getSoltabNames() self.soltab_picker.clear() for l in self.soltab_labels: self.soltab_picker.addItem(l) self._soltab_picker_event() def _soltab_picker_event(self): """Callback function for when the SolTab is changed. Sets the `soltab` attribute. """ self.logger.debug('Soltab changed to: ' + self.soltab_picker.currentText()) self.soltab = self.solset.getSoltab(self.soltab_picker.currentText()) rvals, raxes = reorder_soltab(self.soltab) self.stcache.update(rvals, raxes) def _phasewrap_event(self): self.logger.debug('Phase wrapping changed to ' + str(self.phasewrap_box.isChecked())) self.wrapphase = self.phasewrap_box.isChecked() def _plot_button_event(self): """Callback function for when the plot button is pressed. Calls the `plot` function subsecquently. """ self.logger.debug('Plotting button pressed.') self.plot(labels=(self.axis, self.soltab.name)) def plot(self, labels=('x-axis', 'y-axis'), limits=([None, None], [None, None])): self.logger.info('Plotting ' + self.soltab.name + ' vs ' + self.axis + \ ' for ' + self.solset.name) antenna = self.station_picker.currentRow() refantenna = self.refant_picker.currentIndex() # Values have shape (timestamps, frequencies, antennas, polarizations, directions). values = self.stcache.values[0] if (('rotationmeasure' in self.soltab.name) or ('RMextract' in self.soltab.name) or ('clock' in self.soltab.name)) and (self.axis == 'freq'): self.logger.warning('Rotation Measure does not support frequency axis! Switch to time instead.') return else: x_axis = self.stcache.values[1][self.axis] st_type = self.soltab.getType() print(st_type) fig = plt.figure() ax = fig.add_subplot(111) ax.set_title(self.stations[antenna]) if self.axis == 'time': if 'rotationmeasure' in self.soltab.name: y_axis = values[:, antenna] ax.plot(x_axis, y_axis) elif ('pol' in self.stcache.axes) and ('dir' in self.stcache.axes): if st_type == 'phase': ax.set_ylim(-np.pi, np.pi) # Plot phase-like quantities w.r.t. to a reference antenna. y_axis = values[:, 0, antenna, :, 0] - values[:, 0, refantenna, :, 0] if self.wrapphase: y_axis = wrap_phase(y_axis) elif (st_type == 'clock') or (st_type == 'rotationmeasure'): y_axis = values[:, antenna] else: y_axis = values[:, 0, antenna, :, 0] for i,y in enumerate(y_axis): ax.plot(x_axis, y[:,i], 'h', label=self.stcache.values[1]['pol'][i]) elif 'pol' in self.stcache.axes: if st_type == 'phase': ax.set_ylim(-np.pi, np.pi) # Plot phase-like quantities w.r.t. to a reference antenna. y_axis = values[:, 0, antenna, :] - values[:, 0, refantenna, :] if self.wrapphase: y_axis = wrap_phase(y_axis) elif (st_type == 'clock') or (st_type == 'rotationmeasure'): y_axis = values[:, antenna] else: y_axis = values[:, 0, antenna, :] for i in range(y_axis.shape[1]): ax.plot(x_axis, y_axis[:, i], 'h', label=self.stcache.values[1]['pol'][i]) elif 'dir' in self.stcache.axes: if st_type == 'phase': ax.set_ylim(-np.pi, np.pi) # Plot phase-like quantities w.r.t. to a reference antenna. y_axis = values[:, 0, antenna, 0] - values[:, 0, refantenna, 0] if self.wrapphase: y_axis = wrap_phase(y_axis) elif (st_type == 'clock') or (st_type == 'rotationmeasure'): y_axis = values[:, antenna] else: y_axis = values[:, 0, antenna, 0] ax.plot(x_axis, y_axis[:, i], 'h') elif ('pol' not in self.stcache.axes) and ('dir' not in self.stcache.axes): if (st_type == 'clock') or (st_type == 'rotationmeasure'): y_axis = values[:, antenna] else: y_axis = values[:, 0, antenna] ax.plot(x_axis, y_axis) elif self.axis == 'freq': if ('rotationmeasure' in self.soltab.name) or ('clock' in self.soltab.name): self.logger.warning('Rotation Measure does not support frequency axis! Switch to time instead.') if ('pol' in self.stcache.axes) and ('dir' in self.stcache.axes): if st_type == 'phase': ax.set_ylim(-np.pi, np.pi) # Plot phase-like quantities w.r.t. to a reference antenna. y_axis = values[0, :, antenna, :, 0] - values[0, :, refantenna, :, 0] if self.wrapphase: y_axis = wrap_phase(y_axis) else: y_axis = values[0, :, antenna, :, 0] for i,y in enumerate(y_axis): ax.plot(x_axis, y[:,i]) elif 'pol' in self.stcache.axes: if st_type == 'phase': ax.set_ylim(-np.pi, np.pi) # Plot phase-like quantities w.r.t. to a reference antenna. y_axis = values[0, :, antenna, :] - values[0, :, refantenna, :] if self.wrapphase: y_axis = wrap_phase(y_axis) else: y_axis = values[0, :, antenna, :] for i in range(y_axis.shape[1]): ax.plot(x_axis, y_axis[:, i], 'h', label=self.stcache.values[1]['pol'][i]) elif 'dir' in self.stcache.axes: if st_type == 'phase': ax.set_ylim(-np.pi, np.pi) # Plot phase-like quantities w.r.t. to a reference antenna. y_axis = values[0, :, antenna, 0] - values[0, :, refantenna, 0] if self.wrapphase: y_axis = wrap_phase(y_axis) else: y_axis = values[0, :, antenna, 0] elif ('pol' not in self.stcache.axes) and ('dir' not in self.stcache.axes): y_axis = values[0, :, antenna] ax.plot(x_axis, y_axis) ax.set(xlabel=self.axis, ylabel=labels[1], xlim=limits[0], ylim=limits[1]) if ax.get_legend_handles_labels()[1]: ax.legend() self.figures.append(fig) fig.show()
class DMDWidget(QWidget): sig_request_mask_coordinates = pyqtSignal() sig_start_registration = pyqtSignal() sig_finished_registration = pyqtSignal() def __init__(self, parent=None, *args, **kwargs): super().__init__(*args, **kwargs) self.main_application = parent self.set_transformation_saving_location( os.getcwd() + '/CoordinatesManager/Registration/dmd_transformation') self.init_gui() def init_gui(self): layout = QGridLayout() self.setFixedSize(320, 300) self.box = roundQGroupBox() self.box.setTitle("DMD control") box_layout = QGridLayout() self.box.setLayout(box_layout) self.setLayout(layout) self.connect_button = QPushButton('Connect') self.register_button = QPushButton('Register') lasers = ['640', '532', '488'] self.transform_for_laser_menu = QListWidget() self.transform_for_laser_menu.addItems(lasers) self.transform_for_laser_menu.setFixedHeight(55) self.transform_for_laser_menu.setCurrentRow(0) self.project_button = QPushButton('Start projecting') self.clear_button = QPushButton('Clear memory') self.white_project_button = QPushButton('Full illum.') self.load_mask_container_stack = QStackedWidget() self.connect_button.clicked.connect(self.connect) self.register_button.clicked.connect(lambda: self.register( self.transform_for_laser_menu.selectedItems()[0].text())) self.project_button.clicked.connect(self.project) self.clear_button.clicked.connect(self.clear) self.white_project_button.clicked.connect(self.project_full_white) # Stack page 1 self.load_mask_container_1 = roundQGroupBox() self.load_mask_container_1.setTitle('Load mask') load_mask_container_layout_1 = QGridLayout() self.load_mask_container_1.setLayout(load_mask_container_layout_1) self.load_mask_from_widget_button = QPushButton('From mask generator') self.load_mask_from_file_button = QPushButton('From file') self.load_mask_from_widget_button.clicked.connect( self.load_mask_from_widget) self.load_mask_from_file_button.clicked.connect( self.load_mask_from_memory) load_mask_container_layout_1.addWidget( self.load_mask_from_widget_button, 0, 0) load_mask_container_layout_1.addWidget(self.load_mask_from_file_button, 1, 0) # Stack page 2 self.load_mask_container_2 = roundQGroupBox() self.load_mask_container_2.setTitle('Load mask') load_mask_container_layout_2 = QGridLayout() self.load_mask_container_2.setLayout(load_mask_container_layout_2) self.load_image = QPushButton('Image') self.load_folder = QPushButton('Folder') self.load_video = QPushButton('Video') self.load_image.clicked.connect(self.load_mask_from_file) self.load_folder.clicked.connect(self.load_mask_from_folder) load_mask_container_layout_2.addWidget(self.load_image, 0, 0) load_mask_container_layout_2.addWidget(self.load_folder, 1, 0) load_mask_container_layout_2.addWidget(self.load_video, 2, 0) # Stack page 3 self.load_mask_container_3 = roundQGroupBox() self.load_mask_container_3.setTitle('Load mask') load_mask_container_layout_3 = QGridLayout() self.load_mask_container_3.setLayout(load_mask_container_layout_3) self.frame_rate_textbox = QLineEdit() self.frame_rate_textbox.setValidator(QtGui.QIntValidator()) self.frame_rate_textbox.setText('1000000') self.repeat_imgseq_button = QCheckBox() self.confirm_button = QPushButton('Set') self.confirm_button.clicked.connect(self.set_movie_settings_on_DMD) load_mask_container_layout_3.addWidget(QLabel(u"Frame duration (µs):"), 0, 0) load_mask_container_layout_3.addWidget(self.frame_rate_textbox, 0, 1) load_mask_container_layout_3.addWidget(QLabel('Repeat sequence:'), 1, 0) load_mask_container_layout_3.addWidget(self.repeat_imgseq_button, 1, 1) load_mask_container_layout_3.addWidget(self.confirm_button, 2, 1) ## Add layers to stack self.load_mask_container_stack.addWidget(self.load_mask_container_1) self.load_mask_container_stack.addWidget(self.load_mask_container_2) self.load_mask_container_stack.addWidget(self.load_mask_container_3) box_layout.addWidget(self.connect_button, 0, 0) box_layout.addWidget(self.register_button, 1, 0) box_layout.addWidget(QLabel('To be used with laser:'), 0, 1) box_layout.addWidget(self.transform_for_laser_menu, 1, 1, 2, 1) box_layout.addWidget(self.project_button, 2, 0) box_layout.addWidget(self.clear_button, 3, 0) box_layout.addWidget(self.white_project_button, 3, 1) box_layout.addWidget(self.load_mask_container_stack, 4, 0, 1, 2) layout.addWidget(self.box) self.open_latest_transformation() def connect(self): if self.connect_button.text() == 'Connect': self.DMD = DMDActuator.DMDActuator() self.connect_button.setText('Disconnect') else: self.DMD.disconnect_DMD() del self.DMD self.connect_button.setText('Connect') def register(self, laser): self.sig_start_registration.emit() ## Add control for lasers, signal slot should be there in AOTF widget registrator = Registrator.DMDRegistator(self.DMD) self.transform[laser] = registrator.registration( registration_pattern='circle') self.save_transformation() self.sig_finished_registration.emit() def check_mask_format_valid(self, mask): if len(mask.shape) == 3: print('Image is stack; using max projection') mask = np.max(mask, axis=2) if mask.shape[0] == 1024 and mask.shape[1] == 768: mask = mask.transpose() elif mask.shape[0] != 768 or mask.shape[1] != 1024: print('Image has wrong resolution; should be 1024x768') return False, None return True, mask def load_mask_from_memory(self): """ Open a file manager to browse through files, load image file """ self.load_mask_container_stack.setCurrentIndex(1) def load_mask_from_file(self): self.loadFileName, _ = QtWidgets.QFileDialog.getOpenFileName( self, 'Select file', './CoordinateManager/Images/', "(*.jpg *.png)") image = 255 - plt.imread(self.loadFileName) check, image = self.check_mask_format_valid(image) if check: self.DMD.send_data_to_DMD(image) print('Image loaded') self.load_mask_container_stack.setCurrentIndex(0) def load_mask_from_folder(self): """ Load files from folder using path and save frames in multidimensional array. """ foldername = QtWidgets.QFileDialog.getExistingDirectory( self, 'Select folder', './CoordinateManager/Images/') list_dir_raw = sorted(os.listdir(foldername)) list_dir = [ file for file in list_dir_raw if file[-3:] in ['png', 'jpg'] ] list_nr = len(list_dir) image_sequence = np.zeros([768, 1024, list_nr]) for i in range(list_nr): single_mask = 255 - plt.imread(foldername + '/' + list_dir[i]) check, valid_single_mask = self.check_mask_format_valid( single_mask) if check: image_sequence[:, :, i] = valid_single_mask else: return self.DMD.send_data_to_DMD(image_sequence) self.load_mask_container_stack.setCurrentIndex(2) def set_movie_settings_on_DMD(self): repeat = self.repeat_imgseq_button.isChecked() frame_time = int(self.frame_rate_textbox.text()) self.DMD.set_repeat(repeat) self.DMD.set_timing(frame_time) self.load_mask_container_stack.setCurrentIndex(0) def load_mask_from_widget(self): self.sig_request_mask_coordinates.emit() def receive_mask_coordinates(self, sig): ## Receive untransformed mask coordinates, transform them, create mask, ## send mask to DMD. [list_of_rois, flag_fill_contour, contour_thickness, flag_invert_mode] = sig list_of_rois = self.transform_coordinates(list_of_rois) self.mask = ProcessImage.CreateBinaryMaskFromRoiCoordinates(list_of_rois, \ fill_contour = flag_fill_contour, \ contour_thickness = contour_thickness, \ invert_mask = flag_invert_mode, mask_resolution = (768,1024)) fig, axs = plt.subplots(1, 1) axs.imshow(self.mask) self.DMD.send_data_to_DMD(self.mask) def project_full_white(self): self.DMD.send_data_to_DMD(np.ones((1024, 768))) self.DMD.start_projection() self.project_button.setText('Stop projecting') def interupt_projection(self): if self.project_button.text() == 'Stop projecting': self.DMD.stop_projection() self.DMD.free_memory() self.project_button.setText('Start projecting') def continue_projection(self): self.DMD.stop_projection() self.DMD.free_memory() if self.project_button.text() == 'Stop projecting': self.DMD.send_data_to_DMD(self.mask) self.DMD.start_projection() def transform_coordinates(self, list_of_rois): laser = self.transform_for_laser_menu.selectedItems()[0].text() new_list_of_rois = [] for roi in list_of_rois: new_list_of_rois.append( CoordinateTransformations.transform(roi, self.transform[laser])) return new_list_of_rois def project(self): if self.project_button.text() == 'Start projecting': print('Projecting') self.DMD.start_projection() self.project_button.setText('Stop projecting') else: self.DMD.stop_projection() self.project_button.setText('Start projecting') def clear(self): self.DMD.free_memory() def set_transformation_saving_location(self, filename): self.transformation_file_name = filename def save_transformation(self): for laser, transform in self.transform.items(): size = transform.shape[0] np.savetxt(self.transformation_file_name + laser, np.reshape(transform, (-1, size))) def open_latest_transformation(self): self.transform = {} lasers = ['640', '532', '488'] for laser in lasers: try: transform = np.loadtxt(self.transformation_file_name + laser) except: pass else: print('Transform for ' + laser + ' loaded.') self.transform[laser] = np.reshape(transform, (transform.shape[1], -1, 2)) print(self.transform[laser][:, :, 0]) print(self.transform[laser][:, :, 1])
class SessionsManager(QDialog): """Session Manager, to load different configurations of ninja.""" def __init__(self, parent=None): super(SessionsManager, self).__init__(parent, Qt.Dialog) self._ide = parent self.setWindowTitle(translations.TR_SESSIONS_TITLE) self.setMinimumWidth(400) vbox = QVBoxLayout(self) vbox.addWidget(QLabel(translations.TR_SESSIONS_DIALOG_BODY)) self.sessionList = QListWidget() self.sessionList.addItems([key for key in settings.SESSIONS]) self.sessionList.setCurrentRow(0) self.contentList = QListWidget() self.btnDelete = QPushButton(translations.TR_SESSIONS_BTN_DELETE) self.btnDelete.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.btnUpdate = QPushButton(translations.TR_SESSIONS_BTN_UPDATE) self.btnUpdate.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.btnCreate = QPushButton(translations.TR_SESSIONS_BTN_CREATE) self.btnCreate.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.btnOpen = QPushButton(translations.TR_SESSIONS_BTN_ACTIVATE) self.btnOpen.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.btnOpen.setDefault(True) hbox = QHBoxLayout() hbox.addWidget(self.btnDelete) hbox.addWidget(self.btnUpdate) hbox.addWidget(self.btnCreate) hbox.addWidget(self.btnOpen) vbox.addWidget(self.sessionList) vbox.addWidget(self.contentList) vbox.addLayout(hbox) self.sessionList.itemSelectionChanged.connect(self.load_session_content) self.btnOpen.clicked['bool'].connect(self.open_session) self.btnUpdate.clicked['bool'].connect(self.save_session) self.btnCreate.clicked['bool'].connect(self.create_session) self.btnDelete.clicked['bool'].connect(self.delete_session) self.load_session_content() def load_session_content(self): """Load the selected session, replacing the current session.""" item = self.sessionList.currentItem() self.contentList.clear() if item is not None: key = item.text() files = [translations.TR_FILES] + \ [file[0] for file in settings.SESSIONS[key][0]] projects = [translations.TR_PROJECT] + settings.SESSIONS[key][1] content = files + projects self.contentList.addItems(content) def create_session(self): """Create a new Session.""" sessionInfo = QInputDialog.getText(None, translations.TR_SESSIONS_CREATE_TITLE, translations.TR_SESSIONS_CREATE_BODY) if sessionInfo[1]: sessionName = sessionInfo[0] if not sessionName or sessionName in settings.SESSIONS: QMessageBox.information(self, translations.TR_SESSIONS_MESSAGE_TITLE, translations.TR_SESSIONS_MESSAGE_BODY) return SessionsManager.save_session_data(sessionName, self._ide) self._ide.Session = sessionName self.close() @classmethod def save_session_data(cls, sessionName, ide): """Save the updates from a session.""" openedFiles = ide.filesystem.get_files() files_info = [] for path in openedFiles: editable = ide.get_or_create_editable(path) if editable.is_dirty: stat_value = 0 else: stat_value = os.stat(path).st_mtime files_info.append([path, editable.editor.getCursorPosition(), stat_value]) projects_obj = ide.filesystem.get_projects() projects = [projects_obj[proj].path for proj in projects_obj] settings.SESSIONS[sessionName] = [files_info, projects] qsettings = ide.data_settings() qsettings.setValue('ide/sessions', settings.SESSIONS) def save_session(self): """Save current session""" if self.sessionList.currentItem(): sessionName = self.sessionList.currentItem().text() SessionsManager.save_session_data(sessionName, self._ide) self._ide.show_message(translations.TR_SESSIONS_UPDATED_NOTIF % {'session': sessionName}, 2000) self.load_session_content() def open_session(self): """Open a saved session""" if self.sessionList.currentItem(): key = self.sessionList.currentItem().text() self._load_session_data(key) self._ide.Session = key self.close() def delete_session(self): """Delete a session""" if self.sessionList.currentItem(): key = self.sessionList.currentItem().text() settings.SESSIONS.pop(key) self.sessionList.takeItem(self.sessionList.currentRow()) self.contentList.clear() qsettings = self._ide.data_settings() qsettings.setValue('ide/sessions', settings.SESSIONS) def _load_session_data(self, key): """Activate the selected session, closing the current files/projects""" main_container = self._ide.get_service('main_container') projects_explorer = self._ide.get_service('projects_explorer') if projects_explorer and main_container: projects_explorer.close_opened_projects() for fileData in settings.SESSIONS[key][0]: path, line, stat_value = fileData if file_manager.file_exists(path): mtime = os.stat(path).st_mtime ignore_checkers = (mtime == stat_value) main_container.open_file(path, line, ignore_checkers=ignore_checkers) if projects_explorer: projects_explorer.load_session_projects( settings.SESSIONS[key][1])
class MainWidget(QWidget): icon_path = settings.icon_dir() def __init__(self, parent=None): super().__init__(parent) self.mainwindow = parent self.last_tab = 0 self.last_name = None # for showing teacher in searchbar after adding teacher to class # ----------------create GroupBoxes------------- self.createTLGB() self.createBLGB() self.createTRGB() self.createBRGB() # ----------------end GroupBoxes---------------- # ----------------main Layout------------------- main_layout = QHBoxLayout() left_area = QVBoxLayout() right_area = QVBoxLayout() left_area.addWidget(self.TLGB) left_area.addWidget(self.BLGB) right_area.addWidget(self.TRGB) right_area.addWidget(self.BRGB) main_layout.addLayout(left_area) main_layout.addLayout(right_area) self.setLayout(main_layout) # ----------------end main Layout---------------- def createTLGB(self): """ places GroupBox to top-left """ self.TLGB = QGroupBox('Suchoptionen für Klassen') layout = QVBoxLayout() sublayout_top = QHBoxLayout() sublayout_bot = QHBoxLayout() level_label = QLabel('Klassenstufe: ') self.select_level = QComboBox() self.fill_combo_level() self.hours_missing = QCheckBox('Nur Klassen mit fehlenden Stunden') self.done_classes = QCheckBox('Nur volltändige Klassen') self.spec_teacher = QCheckBox('Nur spezifische Lehrkraft') self.select_teacher = QComboBox() self.fill_combo_teacher() self.select_teacher.setDisabled(True) self.spec_teacher.toggled.connect(self.select_teacher.setEnabled) reset_button = QPushButton('Zurücksetzen') self.select_level.currentTextChanged.connect(self._search_classes) self.hours_missing.stateChanged.connect(self._search_classes) self.done_classes.stateChanged.connect(self._search_classes) self.spec_teacher.stateChanged.connect(self._search_classes) self.select_teacher.currentTextChanged.connect(self._search_classes) reset_button.clicked.connect(self._reset) sublayout_top.addWidget(level_label) sublayout_top.addWidget(self.select_level) sublayout_bot.addWidget(reset_button) #sublayout_bot.addWidget(search_button) layout.addLayout(sublayout_top) layout.addWidget(self.hours_missing) layout.addWidget(self.done_classes) layout.addWidget(self.spec_teacher) layout.addWidget(self.select_teacher) layout.addLayout(sublayout_bot) self.TLGB.setLayout(layout) def fill_combo_teacher(self): self.select_teacher.clear() self.select_teacher.addItems( ['Lehrkraft auswählen'] + [t.name for t in self.mainwindow.allteachers.teachers]) def fill_combo_level(self): self.select_level.clear() self.select_level.addItems(['Alle'] + self.mainwindow.allclasses.list_levels()) def createBLGB(self): """ places GroupBox to bottom-left """ self.BLGB = QGroupBox('Reststunden Lehrer') self.blgb_layout = QHBoxLayout() self.list_area = QListWidget() self._build_teacher_list() self.blgb_layout.addWidget(self.list_area) self.BLGB.setLayout(self.blgb_layout) def createTRGB(self): """ places GroupBox to top-left """ self.TRGB = QGroupBox('Deputat') gb_layout = QVBoxLayout() self.tabs = QTabWidget() self._list_tabs(self.mainwindow.allclasses.classes) layout_tab_bot = QHBoxLayout() add_teacher_button = QPushButton('Lehrer Hinzufügen') add_teacher_button.setIcon( QIcon(os.path.join(self.icon_path, 'add.svg'))) add_class_button = QPushButton('Klasse Hinzufügen') add_class_button.setIcon(QIcon(os.path.join(self.icon_path, 'add.svg'))) add_teacher_button.clicked.connect(self._add_teacher) add_class_button.clicked.connect(self._add_class) layout_tab_bot.addWidget(add_teacher_button) layout_tab_bot.addWidget(add_class_button) gb_layout.addWidget(self.tabs) gb_layout.addLayout(layout_tab_bot) self.TRGB.setLayout(gb_layout) def createBRGB(self): """ places GroupBox to bottom-right """ self.BRGB = QGroupBox('Lehrer') layout = QVBoxLayout() top = QHBoxLayout() self.searchbar = QComboBox() self.fill_combo_teacher_search() top.addWidget(self.searchbar) self.selected = self._selected_teacher() layout.addLayout(top) layout.addLayout(self.selected) self.searchbar.currentTextChanged.connect(self._changed_search) self.BRGB.setLayout(layout) # ----------------end Layout---------------- def fill_combo_teacher_search(self): self.searchbar.clear() self.searchbar.addItems( ['Lehrkraft auswählen'] + [t.name for t in self.mainwindow.allteachers.teachers]) def _build_teacher_list(self): self.list_area.clear() self.list_area.addItems( self.mainwindow.allteachers._list_teacher_hours()) def _add_tab(self, obj): tab = QWidget() layout_tab = QVBoxLayout() for i in obj.subjects: item = self._class_info_item(i, obj.subjects[i], obj) layout_tab.addLayout(item) tab.setLayout(layout_tab) return tab def _selected_teacher(self): selected = QHBoxLayout() self.info = QLabel('') selected.addWidget(self.info) return selected def _changed_search(self): name = self.searchbar.currentText() text = '' for t in self.mainwindow.allteachers.teachers: if t.name == name: text = str(t) if name == 'Lehrkraft auswählen': self.info.setText('') else: self.info.setText(text) if self.last_name: for t in self.mainwindow.allteachers.teachers: if t.name == self.last_name: self.searchbar.setCurrentText(self.last_name) break def _list_available_teachers(self, subject): return ['Lehrkraft wählen'] + [ f'{t.name} ({t.short}) - {t._get_hours_left()} Stunden übrig' for t in self.mainwindow.allteachers.teachers if subject in t.subjects ] def _reset(self): self.hours_missing.setChecked(False) self.done_classes.setChecked(False) self.spec_teacher.setChecked(False) self.select_level.setCurrentText('Alle') self.select_teacher.setCurrentText('Lehrkraft auswählen') self._search_classes() def _search_classes(self): levels = self.select_level.currentText() hours_missing = self.hours_missing.checkState() done_classes = self.done_classes.checkState() teacher = None classes = [] current_text = self.select_teacher.currentText() if self.spec_teacher.checkState( ) and current_text != 'Lehrkraft auswählen': for t in self.mainwindow.allteachers.teachers: if t.name == current_text: teacher = t break for c in self.mainwindow.allclasses.classes: if str(c.level) == levels or levels == 'Alle': classes.append(c) if hours_missing: for c in classes.copy(): if not c.hours_missing( ): #wenn keine stunden fehlen -> entferne Klasse classes.remove(c) if done_classes: for c in classes.copy(): if c.hours_missing(): #wenn Stunden fehlen -> entferne Klasse classes.remove(c) if teacher: for c in classes.copy(): if teacher.short not in c.list_teachers(): classes.remove(c) self._list_tabs(classes) def _list_tabs(self, classes): if self.tabs.currentIndex() != -1: self.last_tab = self.tabs.currentIndex() for i in list(range(self.tabs.count()))[::-1]: self.tabs.removeTab(i) liste = sorted([obj for obj in classes]) for obj in liste: self.tabs.addTab(self._add_tab(obj), obj.get_fullname()) self.tabs.setCurrentIndex(self.last_tab) def _class_info_item(self, short: str, info: list, obj): layout = QHBoxLayout() try: name = subjects(True)[short] except KeyError as error: print(error) hours = str(info[0]) teacher = info[1] name_label = QLabel(name) hours_label = QLabel(hours) teacher_selection = QComboBox() available_teachers = self._list_available_teachers(short) teacher_selection.addItems(available_teachers) if obj.subjects[short][1] == teacher: for i in available_teachers: if teacher in i: teacher_selection.setCurrentText(i) teacher_selection.activated.connect(lambda: self.teacher_added( obj, teacher_selection.currentText(), short)) layout.addWidget(name_label) layout.addWidget(hours_label) layout.addWidget(teacher_selection) return layout def teacher_added(self, klasse, text, short): teacher = None name = None for t in self.mainwindow.allteachers.teachers: if t.short in text: teacher = t break if not self.mainwindow.allclasses.backup: self.mainwindow.allclasses.backup = self.mainwindow.allclasses.classes.copy( ) for c in self.mainwindow.allclasses.classes: if c == klasse: for s in c.subjects: if s != short: continue try: c.subjects[s][1] = teacher.short name = teacher.name except AttributeError: c.subjects[s][1] = 'null' self.last_name = name self._refresh() self.mainwindow.changed = True def _add_class(self): add_c = AddClassPopUp('Klasse Hinzufügen', self) add_c.setGeometry(100, 200, 500, 300) add_c.show() def _add_teacher(self): add_t = AddTeacherPopUp('Lehrer Hinzufügen', self) add_t.setGeometry(100, 200, 500, 300) add_t.show() def _refresh(self): self._changed_search() self._search_classes() self._build_teacher_list() self.fill_combo_teacher() self.fill_combo_level() self.fill_combo_teacher_search()
class SqliteDbTableEditer(QWidget): #Db=sqlite3.connect("test.db") def __init__(self,dbPath,tblName='',parent=None): self.app=QApplication(sys.argv) self.SqliteDbTypes=['integer','real','text','blob'] self.DbPath,self.CurrentTable=dbPath,tblName #连接数据库 self.Db=sqlite3.connect(self.DbPath) #构建Gui组件 super(SqliteDbTableEditer,self).__init__(parent) self.setWindowTitle('Sqlite数据库表修改器') screen=QDesktopWidget().availableGeometry(0) self.setGeometry(screen.width()/3/2-1, screen.height()/5/2-1, screen.width()*2/3, screen.height()*4/5 ) #lay lay=QVBoxLayout() self.setLayout(lay) #数据库表设置控件 ##layDb layDb=QHBoxLayout() lay.addLayout(layDb) ###lblDb lblDb=QLabel('数据库:') layDb.addWidget(lblDb) ###self.leDb self.leDb=QLineEdit() self.leDb.setText(self.DbPath) layDb.addWidget(self.leDb) ###btnDb btnChangeDb=QPushButton('浏览') btnChangeDb.clicked.connect(self.btnChangeDb_Clicked) layDb.addWidget(btnChangeDb) ###lblTbl lblTbl=QLabel('数据表:') layDb.addWidget(lblTbl) ###self.cbbTbls self.cbbTbls=QComboBox() tbls=list(map(lambda x:x[1], list(filter(lambda x:x[0]=='table', self.Db.execute( 'Select * From sqlite_master' ).fetchall() ) ) ) ) self.cbbTbls.addItems(tbls) if self.CurrentTable!='' : self.cbbTbls.setCurrentIndex(tbls.index(self.CurrentTable)) else: self.CurrentTable=tbls[0] self.makeTableInfo() self.cbbTbls.setCurrentIndex(0) layDb.addWidget(self.cbbTbls) ###lblRename lblRename=QLabel('重命名为:') layDb.addWidget(lblRename) ###self.leRename self.leRename=QLineEdit() self.leRename.setFixedWidth(100) layDb.addWidget(self.leRename) ###btnRename btnRenameTable=QPushButton('重命名') btnRenameTable.clicked.connect(self.btnRenameTable_Clicked) layDb.addWidget(btnRenameTable) ###btnDeleteTable btnDeleteTable=QPushButton('删除表') btnDeleteTable.clicked.connect(self.btnDeleteTable_Clicked) layDb.addWidget(btnDeleteTable) ###btnShow self.btnShow=QPushButton('查看表结构') self.btnShow.clicked.connect(self.btnShow_Clicked) layDb.addWidget(self.btnShow) ###设置TableView控件self.tv,以呈现表数据 self.tv=QTableView() lay.addWidget(self.tv) ###self.model基本初始化 self.model=QSqlTableModel(self,QSqlDatabase.addDatabase('QSQLITE')) self.model.setEditStrategy(QSqlTableModel.OnFieldChange) ###self.tv链接到数据源 self.tv.setModel(self.model) ###self.model数据初始化 self.model.database().setDatabaseName(self.DbPath) self.model.database().open() self.model.setTable(self.CurrentTable) self.model.select() self.cbbTbls.currentIndexChanged.connect(self.changeTable) ##layBtns layBtns=QHBoxLayout() lay.addLayout(layBtns) ###btnAddColumn btnAddColumn=QPushButton('添加列') btnAddColumn.setToolTip('给当前表添加列') btnAddColumn.clicked.connect(self.btnAddColumn_Clicked) layBtns.addWidget(btnAddColumn) ###btnDeleteColumn btnDeleteColumn=QPushButton('删除列') btnDeleteColumn.setToolTip('删除当前表的列') btnDeleteColumn.clicked.connect(self.btnDeleteColumn_Clicked) layBtns.addWidget(btnDeleteColumn) ###btnRenameColumn btnRenameColumn=QPushButton('重命名列') btnRenameColumn.setToolTip('重命名当前表的列') btnRenameColumn.clicked.connect(self.btnRenameColumn_Clicked) layBtns.addWidget(btnRenameColumn) ###btnModifyColumnType btnModifyColumnType=QPushButton('修改列数据类型') btnModifyColumnType.setToolTip('修改当前表的列的数据类型') btnModifyColumnType.clicked.connect(self.btnModifyColumnType_Clicked) layBtns.addWidget(btnModifyColumnType) ###btnModifyColumnConstraint btnModifyColumnConstraint=QPushButton('修改列约束') btnModifyColumnConstraint.setToolTip('修改当前表的列的约束') btnModifyColumnConstraint.clicked.connect( self.btnModifyColumnConstraint_Clicked) layBtns.addWidget(btnModifyColumnConstraint) ###btnOrderColumns btnOrderColumns=QPushButton('调整列顺序') btnOrderColumns.setToolTip('调整当前表的列的顺序') btnOrderColumns.clicked.connect(self.btnOrderColumns_Clicked) layBtns.addWidget(btnOrderColumns) ###btnModifyTableStruct btnModifyTableStruct=QPushButton('修改表结构') btnModifyTableStruct.setToolTip('功能:1.增加列;2.删除列;' +'3.修改列名;4.修改列类型;' +'5.修改列约束;6.调整列顺序' ) btnModifyTableStruct.clicked.connect(self.btnModifyTableStruct_Clicked) layBtns.addWidget(btnModifyTableStruct) ###btnInsertRow btnInsertRow=QPushButton('插入行') btnInsertRow.setToolTip('将在数据表最后增加一行新记录') btnInsertRow.clicked.connect(self.btnInsertRow_Clicked) layBtns.addWidget(btnInsertRow) ###btnDeleteRows btnDeleteRows=QPushButton('删除行') btnDeleteRows.setToolTip('删除所有选中项所在的行') btnDeleteRows.clicked.connect(self.btnDeleteRows_Clicked) layBtns.addWidget(btnDeleteRows) ###btnQuery btnQuery=QPushButton('查询数据') btnQuery.setToolTip('对当前表或数据库进行查询,查询语句将被直接链接到self.model上') btnQuery.clicked.connect(self.btnQuery_Clicked) layBtns.addWidget(btnQuery) self.show() self.app.exec_() def __del__(self): #销毁多余数据库连接 #self.Db.commit() self.Db.close() #---------------------------------------------------------------- def makeTableInfo(self): #table_info=self.Db.execute('pragma table_info(%s)'%self.CurrentTable).fetchall() paragmastr="pragma table_info( '" + self.CurrentTable + "' ) " table_info=self.Db.execute(paragmastr).fetchall() self.columnsCount=len(table_info) self.columnsName=list(map(lambda x:x[1],table_info)) self.columnsType=list(map(lambda x:x[2],table_info)) dbinfo=self.Db.execute('select * from sqlite_master').fetchall() for x in dbinfo: if x[0]=='table' and x[1]==self.CurrentTable: self.sqlStr=x[4] break def DeleteColumn(self,tableName,columnName,tempName=''): if tempName=='': #tempName==''表示直接删除对应的列并提交数据库更改 tempName=tableName+'temp' sqlite_master_sql="select * from sqlite_master" sqlite_master=self.Db.execute(sqlite_master_sql).fetchall() createStr=filter(lambda x:x[0]=='table' and x[1]==tableName, self.Db.execute('select * from sqlite_master').fetchall())[0][4] createStr=','.join(filter(lambda x:x.find(columnName)==-1,createStr.split(','))) newColumns=','.join(map(lambda x:x[1],self.Db.execute('Pragma table_info(%s)'%tableName).fetchall())) #将旧表重命名为临时表名 self.Db.execute("Alter Table %s Rename To %s"%(tableName,tempName)) #新建删除了指定列的数据表 self.Db.execute(createStr) #将旧表的数据导入新表 self.Db.execute('Insert Into %s Select %s From %s'% (tableName,newColumns,tempName)) #删除旧表 self.Db.execute('Drop Table %s'%tempName) #---------------------------------------------------------------- def btnChangeDb_Clicked(self,event): pt=QFileDialog.getOpenFileName( caption='请选择一个sqlite数据库文件:', filter='sqlite数据库文件 (*.db)', directory=os.path.dirname(self.DbPath) ) p=pt[0] if platform.system()=='Windows': p=p.replace('/','\\') if os.path.exists(p): self.DbPath=p self.Db=sqlite3.connect(self.DbPath) tbls=map(lambda x:x[1], filter(lambda x:x[0]=='table', self.Db.execute( 'Select * From sqlite_master' ).fetchall() ) ) self.cbbTbls.currentIndexChanged.disconnect(self.changeTable) self.cbbTbls.clear() self.cbbTbls.addItems(tbls) self.cbbTbls.currentIndexChanged.connect(self.changeTable) self.CurrentTable=tbls[0] self.cbbTbls.setCurrentIndex(0) self.leDb.setText(p) self.model.database().setDatabaseName(self.DbPath) self.model.database().open() self.model.setTable(self.CurrentTable) self.model.select() def changeTable(self,event): if self.CurrentTable!=self.cbbTbls.itemText(event): self.CurrentTable=self.cbbTbls.itemText(event) self.model.setTable(self.CurrentTable) self.model.select() self.makeTableInfo() self.btnShow.setText('查看表结构') def btnDeleteTable_Clicked(self,event): self.Db.execute('Drop Table %s'%self.CurrentTable) for i in range(self.cbbTbls.count()-1,-1,-1): if self.cbbTbls.itemText(i)==self.CurrentTable: self.cbbTbls.removeItem(i) break self.CurrentTable=self.cbbTbls.itemText(0) self.model.setTable(self.CurrentTable) self.model.select() def btnRenameTable_Clicked(self,event): if self.leRename.text()!='': if self.leRename.text()!=self.CurrentTable: try: self.Db.execute('Alter Table %s Rename To %s'% (self.CurrentTable,self.leRename.text()) ) except sqlite3.OperationalError as e: if e.message=='there is already another table or index with this name: %s'%self.leRename.text(): QMessageBox.information(self,'错误', '抱歉,本数据库中以“'+self.leRename.text()+ '”为名称的表或索引已经存在,无法完'+ '成重命名,请重新输入一个名称', '知道了') else: QMessageBox.information(self,'错误', '抱歉,可能是因表名包含非法字符,故'+ '无法完成重命名,请重新输入表名', '知道了') self.leRename.setText('') return self.CurrentTable=self.leRename.text() self.cbbTbls.setItemText(self.cbbTbls.currentIndex(), self.CurrentTable ) self.model.clear() self.model.setQuery(QSqlQuery( 'Select * From %s'%self.CurrentTable)) self.model.select() self.leRename.setText('') else: QMessageBox.information(self,'注意', '抱歉,你还没有输入当前表要修改成的表名\n\n'+ '请先在文本框里输入当前表要重命名成的名字,再点击我', '知道了') def btnShow_Clicked(self,event): if self.btnShow.text()=='查看表结构': self.model.setTable('') self.model.setQuery(QSqlQuery( 'pragma table_info(%s)'%self.CurrentTable)) self.model.select() self.btnShow.setText('查看表数据') else: self.model.setTable(self.CurrentTable) self.model.select() self.btnShow.setText('查看表结构') #---------------------------------------------------------------- def btnInsertRow_Clicked(self,event): self.dlg_InsertRow_Values=[] #self.dlg self.dlg=QDialog() self.dlg.setWindowTitle('插入数据行:') #lay lay=QVBoxLayout() self.dlg.setLayout(lay) #lblprompt lblprompt=QLabel( '请参照创建此表的Sql字符串:\n'+self.sqlStr+ '\n设置各个字段的数据:') lay.addWidget(lblprompt) #layG layG=QGridLayout() lay.addLayout(layG) for i in range(len(self.columnsName)): #lbl lbl=QLabel(self.columnsName[i]+'('+self.columnsType[i]+'):') lbl.setAlignment(Qt.AlignRight) layG.addWidget(lbl,i,0) #le le=QLineEdit() layG.addWidget(le,i,1) if self.columnsType[i].lower() not in self.SqliteDbTypes: #cbb cbb=QComboBox() cbb.addItems(self.SqliteDbTypes) cbb.setCurrentIndex(2) cbb.setToolTip( '此字段的数据类型不是sqlite标准数据'+ '类型,请设置其存储时的使用的sqlite数据类型') layG.addWidget(cbb,i,2) self.dlg_InsertRow_Values.append((le,cbb)) else: self.dlg_InsertRow_Values.append((le,self.columnsType[i])) layG.setColumnStretch(1,1) #layH layH=QHBoxLayout() lay.addLayout(layH) #btnOk btnOk=QPushButton('确定') btnOk.clicked.connect(self.dlg_InsertRow_btnOk_Clicked) layH.addWidget(btnOk) #btnCancel btnCancel=QPushButton('取消') btnCancel.clicked.connect(self.dlg.close) layH.addWidget(btnCancel) self.dlg.show() def dlg_InsertRow_btnOk_Clicked(self,event): sqlStr="Insert Into %s Values("%self.CurrentTable for item in self.dlg_InsertRow_Values: if item[0].text()!='': if type(item[1])==QComboBox: print (item[0].text(),item[1].currentText()) else: print (item[0].text(),item[1]) else: pass def btnDeleteRows_Clicked(self,event): rs=list(map(lambda x:x.row(),self.tv.selectedIndexes())) if len(rs)==0: QMessageBox.information(self,'提醒','请先选中至少一行,再点击此按钮!') return for i in reversed(rs): self.model.removeRows(i,1) self.model.submitAll() def btnQuery_Clicked(self,event): sqltxt,ok=QInputDialog.getText(self,'查询语句设置', '参照创建此表的Sql字符串:\n'+self.sqlStr+ '\n请输入要设置到self.model的查询语句:') if ok: self.model.setTable('') self.model.setQuery(QSqlQuery(sqltxt)) self.model.select() #---------------------------------------------------------------- def btnAddColumn_Clicked(self,event): self.dlgMake_AddColumn() def dlgMake_AddColumn(self,lay=None): if lay is None: self.dlg=QDialog(self) self.dlg.setWindowTitle('添加列:') else: ##self.grpAddColumn self.grpAddColumn=QGroupBox('添加列:') self.grpAddColumn.setCheckable(True) self.grpAddColumn.setChecked(True) lay.addWidget(self.grpAddColumn) ###layAddColumn layAddColumn=QVBoxLayout() if lay is None: self.dlg.setLayout(layAddColumn) else: self.grpAddColumn.setLayout(layAddColumn) ####self.grpAddColumn_ByCmdArgs self.grpAddColumn_ByCmdArgs=QGroupBox('使用参数创建列:') self.grpAddColumn_ByCmdArgs.setCheckable(True) self.grpAddColumn_ByCmdArgs.setChecked(True) self.PreviousChecked=0 self.grpAddColumn_ByCmdArgs.toggled.connect( self.grpAddColumn_ByCmd_toggled) layAddColumn.addWidget(self.grpAddColumn_ByCmdArgs) #####layAddColumn_ByCmdArgs layAddColumn_ByCmdArgs=QHBoxLayout() self.grpAddColumn_ByCmdArgs.setLayout(layAddColumn_ByCmdArgs) ####lblAddColumn_select lblAddColumn_name=QLabel('列名:') layAddColumn_ByCmdArgs.addWidget(lblAddColumn_name) ####self.leAddColumn_name self.leAddColumn_name=QLineEdit() self.leAddColumn_name.setFixedWidth(100) layAddColumn_ByCmdArgs.addWidget(self.leAddColumn_name) ######lblAddColumn_type lblAddColumn_type=QLabel('类型:') layAddColumn_ByCmdArgs.addWidget(lblAddColumn_type) ######self.cbbAddColumn_type self.cbbAddColumn_type=QComboBox() self.cbbAddColumn_type.addItems(self.SqliteDbTypes) self.cbbAddColumn_type.setCurrentIndex(0) self.cbbAddColumn_type.setEditable(True) layAddColumn_ByCmdArgs.addWidget(self.cbbAddColumn_type) ######lblAddColumn_constraint lblAddColumn_constraint=QLabel('约束字符串:') layAddColumn_ByCmdArgs.addWidget(lblAddColumn_constraint) ######self.leAddColumn_constraint self.leAddColumn_constraint=QLineEdit() layAddColumn_ByCmdArgs.addWidget(self.leAddColumn_constraint) ####self.grpAddColumn_ByCmdStr self.grpAddColumn_ByCmdStr=QGroupBox('使用sql字符串创建列:') self.grpAddColumn_ByCmdStr.setCheckable(True) self.grpAddColumn_ByCmdStr.setChecked(False) self.grpAddColumn_ByCmdStr.toggled.connect( self.grpAddColumn_ByCmd_toggled) layAddColumn.addWidget(self.grpAddColumn_ByCmdStr) #####layAddColumn_ByCmdStr layAddColumn_ByCmdStr=QHBoxLayout() self.grpAddColumn_ByCmdStr.setLayout(layAddColumn_ByCmdStr) ######lblAddColumn_cmdstr lblAddColumn_cmdstr=QLabel('用来增加列的部分或完整Sql字符串:') layAddColumn_ByCmdStr.addWidget(lblAddColumn_cmdstr) ######self.leAddColumn_cmdstr self.leAddColumn_cmdstr=QLineEdit() layAddColumn_ByCmdStr.addWidget(self.leAddColumn_cmdstr) if lay is None: self.dlg.show() def grpAddColumn_ByCmd_toggled(self,event): if self.PreviousChecked==0: self.grpAddColumn_ByCmdStr.setChecked(True) self.grpAddColumn_ByCmdArgs.setChecked(False) self.PreviousChecked=1 else: self.grpAddColumn_ByCmdArgs.setChecked(True) self.grpAddColumn_ByCmdStr.setChecked(False) self.PreviousChecked=0 #---------------------------------------------------------------- def btnDeleteColumn_Clicked(self,event): self.dlgMake_DeleteColumn() def dlgMake_DeleteColumn(self,lay=None): if lay is None: self.dlg=QDialog(self) self.dlg.setWindowTitle('删除列:') else: ##self.grpDeleteColumn self.grpDeleteColumn=QGroupBox('删除列:') self.grpDeleteColumn.setCheckable(True) self.grpDeleteColumn.setChecked(False) lay.addWidget(self.grpDeleteColumn) ###layDeleteColumn layDeleteColumn=QHBoxLayout() if lay is None: self.dlg.setLayout(layDeleteColumn) else: self.grpDeleteColumn.setLayout(layDeleteColumn) ###layColumnList layColumnList=QVBoxLayout() layDeleteColumn.addLayout(layColumnList) ####lblDeleteColumn lblDeleteColumn=QLabel('原有的所有列:') layColumnList.addWidget(lblDeleteColumn) ####self.lstColumnList self.lstColumnList=QListWidget() self.lstColumnList.addItems(self.columnsName) self.lstColumnList.setFixedWidth(150) layColumnList.addWidget(self.lstColumnList) ###layDeleteBtns layDeleteBtns=QVBoxLayout() layDeleteColumn.addLayout(layDeleteBtns) ####btnDeleteColumn_Store btnDeleteColumn_Store=QPushButton('>>') btnDeleteColumn_Store.setFixedWidth(50) layDeleteBtns.addWidget(btnDeleteColumn_Store) ####btnDeleteColumn_Unstore btnDeleteColumn_Unstore=QPushButton('<<') btnDeleteColumn_Unstore.setFixedWidth(50) layDeleteBtns.addWidget(btnDeleteColumn_Unstore) ###layColumnsToDelete layColumnsToDelete=QVBoxLayout() layDeleteColumn.addLayout(layColumnsToDelete) ####lblColumnsToDelete lblColumnsToDelete=QLabel('要删除的列:') layColumnsToDelete.addWidget(lblColumnsToDelete) ####self.lstColumnsToDelete self.lstColumnsToDelete=QListWidget() self.lstColumnsToDelete.setFixedWidth(150) layColumnsToDelete.addWidget(self.lstColumnsToDelete) if lay is None: self.dlg.show() #---------------------------------------------------------------- def btnRenameColumn_Clicked(self,event): self.dlgMake_RenameColumn() def dlgMake_RenameColumn(self,lay=None): if lay is None: self.dlg=QDialog(self) self.dlg.setWindowTitle('重命名列:') else: ##self.grpRenameColumn self.grpRenameColumn=QGroupBox('重命名列:') self.grpRenameColumn.setCheckable(True) self.grpRenameColumn.setChecked(False) lay.addWidget(self.grpRenameColumn) ###layRenameColumn layRenameColumn=QHBoxLayout() if lay is None: self.dlg.setLayout(layRenameColumn) else: self.grpRenameColumn.setLayout(layRenameColumn) ####lblRenameColumn_select lblRenameColumn_select=QLabel('选择列:') layRenameColumn.addWidget(lblRenameColumn_select) ####self.cbbRenameColumn_select self.cbbRenameColumn_select=QComboBox() self.cbbRenameColumn_select.addItems(self.columnsName) layRenameColumn.addWidget(self.cbbRenameColumn_select) ####lblRenameColumn_renameto lblRenameColumn_renameto=QLabel('重命名为:') layRenameColumn.addWidget(lblRenameColumn_renameto) ####self.leRenameColumn_renameto self.leRenameColumn_renameto=QLineEdit() self.leRenameColumn_renameto.setFixedWidth(80) layRenameColumn.addWidget(self.leRenameColumn_renameto) ####btnRenameColumn_Store btnRenameColumn_Store=QPushButton('标记 >>') layRenameColumn.addWidget(btnRenameColumn_Store) ####self.cbbRenameColumn_Store self.cbbRenameColumn_Store=QComboBox() layRenameColumn.addWidget(self.cbbRenameColumn_Store,1) if lay is None: self.dlg.show() #---------------------------------------------------------------- def btnModifyColumnType_Clicked(self,event): self.dlgMake_ModifyColumnType() def dlgMake_ModifyColumnType(self,lay=None): if lay is None: self.dlg=QDialog(self) self.dlg.setWindowTitle('修改列数据类型:') else: ##self.grpModifyColumnType self.grpModifyColumnType=QGroupBox('修改列数据类型:') self.grpModifyColumnType.setCheckable(True) self.grpModifyColumnType.setChecked(False) lay.addWidget(self.grpModifyColumnType) ###layModifyColumnType layModifyColumnType=QHBoxLayout() if lay is None: self.dlg.setLayout(layModifyColumnType) else: self.grpModifyColumnType.setLayout(layModifyColumnType) ####lblModifyColumnType_select lblModifyColumnType_select=QLabel('选择列:') layModifyColumnType.addWidget(lblModifyColumnType_select) ####self.cbbModifyColumnType_select self.cbbModifyColumnType_select=QComboBox() self.cbbModifyColumnType_select.addItems(self.columnsName) layModifyColumnType.addWidget(self.cbbModifyColumnType_select) ####lblModifyColumnType_modifyto lblModifyColumnType_modifyto=QLabel('改类型为:') layModifyColumnType.addWidget(lblModifyColumnType_modifyto) ####self.cbbModifyColumnType_modifyto self.cbbModifyColumnType_modifyto=QComboBox() self.cbbModifyColumnType_modifyto.setEditable(True) self.cbbModifyColumnType_modifyto.addItems(self.SqliteDbTypes) self.cbbModifyColumnType_modifyto.setCurrentIndex(2) self.cbbModifyColumnType_modifyto.setFixedWidth(80) layModifyColumnType.addWidget(self.cbbModifyColumnType_modifyto) ####btnModifyColumnType_Store btnModifyColumnType_Store=QPushButton('标记 >>') layModifyColumnType.addWidget(btnModifyColumnType_Store) ####self.cbbModifyColumnType_Store self.cbbModifyColumnType_Store=QComboBox() layModifyColumnType.addWidget(self.cbbModifyColumnType_Store,1) if lay is None: self.dlg.show() #---------------------------------------------------------------- def btnModifyColumnConstraint_Clicked(self,event): self.dlgMake_ModifyColumnConstraint() def dlgMake_ModifyColumnConstraint(self,lay=None): if lay is None: self.dlg=QDialog(self) self.dlg.setWindowTitle('修改列约束:') else: ##self.grpModifyColumnConstraint self.grpModifyColumnConstraint=QGroupBox('修改列约束:') self.grpModifyColumnConstraint.setCheckable(True) self.grpModifyColumnConstraint.setChecked(False) lay.addWidget(self.grpModifyColumnConstraint) ###layModifyColumnConstraint layModifyColumnConstraint=QHBoxLayout() if lay is None: self.dlg.setLayout(layModifyColumnConstraint) else: self.grpModifyColumnConstraint.setLayout(layModifyColumnConstraint) ####lblModifyColumnConstraint_select lblModifyColumnConstraint_select=QLabel('选择列:') layModifyColumnConstraint.addWidget(lblModifyColumnConstraint_select) ####self.cbbModifyColumnConstraint_select self.cbbModifyColumnConstraint_select=QComboBox() self.cbbModifyColumnConstraint_select.addItems(self.columnsName) layModifyColumnConstraint.addWidget(self.cbbModifyColumnConstraint_select) ####lblModifyColumnConstraint_modifyto lblModifyColumnConstraint_modifyto=QLabel('约束改为:') layModifyColumnConstraint.addWidget(lblModifyColumnConstraint_modifyto) ####self.leModifyColumnConstraint_modifyto self.leModifyColumnConstraint_modifyto=QLineEdit() self.leModifyColumnConstraint_modifyto.setFixedWidth(80) layModifyColumnConstraint.addWidget(self.leModifyColumnConstraint_modifyto) ####btnModifyColumnConstraint_Store btnModifyColumnConstraint_Store=QPushButton('标记 >>') layModifyColumnConstraint.addWidget(btnModifyColumnConstraint_Store) ####self.cbbModifyColumnConstraint_Store self.cbbModifyColumnConstraint_Store=QComboBox() layModifyColumnConstraint.addWidget(self.cbbModifyColumnConstraint_Store,1) if lay is None: self.dlg.show() #---------------------------------------------------------------- def btnOrderColumns_Clicked(self,event): self.dlgMake_OrderColumns() def dlgMake_OrderColumns(self,lay=None): if lay is None: self.dlg=QDialog(self) self.dlg.setWindowTitle('调整列顺序:') else: ##self.grpAdjustColumnOrder self.grpAdjustColumnOrder=QGroupBox('调整列顺序:') self.grpAdjustColumnOrder.setCheckable(True) self.grpAdjustColumnOrder.setChecked(False) lay.addWidget(self.grpAdjustColumnOrder) ###layAdjustColumnOrder layAdjustColumnOrder=QVBoxLayout() if lay is None: self.dlg.setLayout(layAdjustColumnOrder) else: self.grpAdjustColumnOrder.setLayout(layAdjustColumnOrder) ####lblAdjustColumnOrder lblAdjustColumnOrder=QLabel('请调整列顺序:') layAdjustColumnOrder.addWidget(lblAdjustColumnOrder) ####self.lstAdjustColumnOrder self.lstAdjustColumnOrder=QListWidget() self.lstAdjustColumnOrder.addItems(self.columnsName) self.lstAdjustColumnOrder.setFixedWidth(150) layAdjustColumnOrder.addWidget(self.lstAdjustColumnOrder) if lay is None: self.dlg.setFixedWidth(175) self.dlg.show() #---------------------------------------------------------------- def btnModifyTableStruct_Clicked(self,event): self.dlg=QDialog(self) self.dlg.setWindowTitle(self.CurrentTable+'表结构修改:') self.dlg.setWindowFlags(Qt.Window| Qt.MSWindowsFixedSizeDialogHint ) #lay lay=QVBoxLayout() self.dlgMake_AddColumn(lay) self.dlgMake_RenameColumn(lay) self.dlgMake_ModifyColumnType(lay) self.dlgMake_ModifyColumnConstraint(lay) #layLists layLists=QHBoxLayout() lay.addLayout(layLists) self.dlgMake_DeleteColumn(layLists) self.dlgMake_OrderColumns(layLists) ##layBtns layBtns=QHBoxLayout() lay.addLayout(layBtns) ##btnOk btnOk=QPushButton('提交修改') btnOk.clicked.connect(self.btnOk_Clicked) layBtns.addWidget(btnOk) ##btnCancel btnCancel=QPushButton('放弃修改') btnCancel.clicked.connect(self.btnCancel_Clicked) layBtns.addWidget(btnCancel) self.dlg.setLayout(lay) self.dlg.open() def btnOk_Clicked(self,event): #do something here self.dlg.close() def btnCancel_Clicked(self,event): self.dlg.close()
class Ui_ThirdOutput(object): def ReturnBack(self): self.window = QtWidgets.QMainWindow() self.ui = Ui_ThirdOutput() self.ui.setupUi(self.window) #Ui_ThirdOutput.hide() self.window.show() def setupUi(self, ThirdOutput): ThirdOutput.setObjectName("ThirdOutput") ThirdOutput.resize(1140, 860) self.centralwidget = QtWidgets.QWidget(ThirdOutput) self.centralwidget.setObjectName("centralwidget") self.BackgroundImage = QtWidgets.QLabel(self.centralwidget) self.BackgroundImage.setGeometry(QtCore.QRect(10, 10, 1111, 811)) self.BackgroundImage.setText("") #Seting backgorund image. Set the path where third.pic.png is saved. self.BackgroundImage.setPixmap( QtGui.QPixmap( "G:/Nick/MSC Data Science/6th Semester/Capstone Project/Practice/New folder/third_pic.jpg" )) self.BackgroundImage.setScaledContents(True) self.BackgroundImage.setObjectName("BackgroundImage") self.Third_Label = QtWidgets.QLabel(self.centralwidget) self.Third_Label.setGeometry(QtCore.QRect(320, 40, 531, 101)) font = QtGui.QFont() font.setPointSize(16) font.setBold(True) font.setWeight(75) self.Third_Label.setFont(font) self.Third_Label.setLayoutDirection(QtCore.Qt.LeftToRight) self.Third_Label.setAlignment(QtCore.Qt.AlignCenter) self.Third_Label.setObjectName("Third_Label") self.backButton = QtWidgets.QPushButton(self.centralwidget) self.backButton.setGeometry(QtCore.QRect(470, 680, 241, 61)) font = QtGui.QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.backButton.setFont(font) self.backButton.setObjectName("backButton") #Option to go back linked with click button self.backButton.clicked.connect(self.ReturnBack) ThirdOutput.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(ThirdOutput) self.menubar.setGeometry(QtCore.QRect(0, 0, 1140, 26)) self.menubar.setObjectName("menubar") ThirdOutput.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(ThirdOutput) self.statusbar.setObjectName("statusbar") ThirdOutput.setStatusBar(self.statusbar) self.retranslateUi(ThirdOutput) QtCore.QMetaObject.connectSlotsByName(ThirdOutput) def retranslateUi(self, ThirdOutput): _translate = QtCore.QCoreApplication.translate ThirdOutput.setWindowTitle(_translate("ThirdOutput", "MainWindow")) #Text in Title self.Third_Label.setText( _translate("ThirdOutput", "Classification Results for Selected Files")) #Text included in button self.backButton.setText( _translate("ThirdOutput", "Back to File Selection")) filename = QFileDialog.getOpenFileNames() # print(filename) path = filename[0] print(path) print(len(path)) ## if len(path) == 0: msg = QMessageBox() msg.setWindowTitle("Received Documents Info") msg.setText("Please insert at least 1 document") msg.setIcon(QMessageBox.Critical) x = msg.exec_() # this will show our messagebox elif len(path) > 0: msg = QMessageBox() msg.setWindowTitle("Received Documents Info") msg.setText("Correct Documents Input") #Below set path where tick.png is saved msg.setIconPixmap( QtGui.QPixmap( "G:/Nick/MSC Data Science/6th Semester/Capstone Project/Practice/New folder/tick.PNG" )) x = msg.exec_() # this will show our messagebox array2 = [] data2 = pd.DataFrame() counter = 0 for i in path: j = prepare(i) proba = model.predict_proba([j]) array2.append(proba[0]) ###### pdf = wi(filename=i, resolution=300) # fn replaced with i pdfimage = pdf.convert('tiff') pg = 1 for img in pdfimage.sequence: counter = counter + 1 pgn = str(pg) page = wi(image=img) page.save(filename=str(i + pgn) + '.tiff') # fn replaced with i pg += 1 print(">> done ", counter, ">>") ###### ###### root = os.listdir('G:/Capstone_Files/images') pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" images = [ cv2.imread(file, 0) for file in glob.glob('G:/Capstone_Files/images/*1.tiff') ] NoneType = type(None) ###### #Preprocces for any new inserted document in order to be prepared for text based classifier array = [] data = pd.DataFrame([]) total_info = [] count = 0 for i in images: image2 = preprocess(i) rotate = rotate_image(image2) if type(rotate) == NoneType: total_df = pytesseract.image_to_data(image2, lang='ell', output_type='data.frame') else: total_df = pytesseract.image_to_data(rotate, lang='ell', output_type='data.frame') total_df = total_df[total_df.conf > 59] total_df = total_df[total_df.text != ''] total_df = total_df[['text']] total_df['document'] = count total_df['lowercase'] = total_df['text'].str.lower() total_df[['our_corrected']] = total_df[['lowercase' ]].applymap(correction) total_df[['enchant_corrected' ]] = total_df[['lowercase']].applymap(enchant_correction) total_df['final_text'] = total_df.apply( lambda r: (r['our_corrected'] + r['enchant_corrected']) if r['our_corrected'] == "" else r['our_corrected'], axis=1) final_series = total_df.groupby('document')['final_text'].apply( list) final_df = pd.DataFrame(final_series) final_df['final_text_string'] = [ ' '.join(map(str, l)) for l in final_df['final_text'] ] doc_info = final_df['final_text_string'].tolist() total_info.extend(doc_info) doc_df_transformed = loaded_vectorizer.transform( [final_df['final_text_string']]) conf_table2 = loaded_model.predict_proba(doc_df_transformed) array.append(conf_table2[0]) data_final = data.append(pd.DataFrame(array), ignore_index=True) data_final = data_final.round(2) * 100 count = count + 1 # EXTRACTED WORDS FROM EVERY DOCUMENT a = [] for i in range(1, len(total_info) + 1): a.append(str(i)) b = ["Extracted Words from Document " + i for i in a] c = [i + ": " for i in b] total_info = [c[i] + total_info[i] for i in range(len(total_info))] self.listWidget = QListWidget() self.listWidget.addItems(total_info) self.listWidget.show() #=========================================================================================================== # BARPLOTS PRESENTING THE PROBABILITY FOR EVERY DOCUMENT FOR THE TWO MODELS data2 = data2.append(array2) data2.columns = [ "Purchase Receipt", "Service Receipt", "Police Report", "ΙΒΑΝ", "Contract", "Claim Statement" ] data2 = data2.rename(index=lambda x: x + 1) data2.index = data2.index.map(str) data2 = data2.rename(index=lambda x: "Document " + x) data2 = data2.round(2) * 100 fig, axarr = plt.subplots(2, 1, figsize=(22, 10), sharex=True) matplotlib.style.use('fivethirtyeight') data_final.plot.bar(ax=axarr[0], width=1.5) axarr[0].set_title("Text Based Classifier", fontsize=20, fontweight="bold", color="brown") axarr[0].get_legend().remove() data2.plot.bar(ax=axarr[1], width=1.5) axarr[1].set_title("Image Based Classifier", fontsize=20, fontweight="bold", color="brown") axarr[1].get_legend().remove() fig.legend( data2, # The line objects #labels=line_labels, # The labels for each line loc="center right", # Position of legend borderaxespad=2.2, # Small spacing around legend box facecolor="white", title="Legend", # Title for the legend title_fontsize=20, frameon=True, edgecolor="black") fig.text(0.04, 0.5, 'Probabilityy for each class', va='center', rotation='vertical', fontsize=20) plt.setp(plt.xticks()[1], rotation=0) plt.suptitle('Class Probability for each Document for both methods', fontsize=28, fontweight="bold") plt.subplots_adjust(right=0.85)
class Lookup(QWidget): MODEL_CLASS = None def __init__(self, parent, model): QWidget.__init__(self, parent, Qt.Window) self.model = model self.model.view = self self._setupUi() self.searchEdit.searchChanged.connect(self.searchChanged) self.searchEdit.returnPressed.connect(self.returnPressed) self.namesList.currentRowChanged.connect(self.currentRowChanged) self.namesList.itemDoubleClicked.connect(self.itemDoubleClicked) self._shortcutUp.activated.connect(self.upPressed) self._shortcutDown.activated.connect(self.downPressed) def _setupUi(self): self.setWindowTitle(tr("Lookup")) self.resize(314, 331) self.verticalLayout = QVBoxLayout(self) self.searchEdit = SearchEdit(self) self.verticalLayout.addWidget(self.searchEdit) self.namesList = QListWidget(self) self.namesList.setEditTriggers(QAbstractItemView.NoEditTriggers) self.namesList.setSelectionBehavior(QAbstractItemView.SelectRows) self.namesList.setUniformItemSizes(True) self.namesList.setSelectionRectVisible(True) self.verticalLayout.addWidget(self.namesList) self.searchEdit.immediate = True self._shortcutUp = QShortcut(self.searchEdit) self._shortcutUp.setKey(QKeySequence(Qt.Key_Up)) self._shortcutUp.setContext(Qt.WidgetShortcut) self._shortcutDown = QShortcut(self.searchEdit) self._shortcutDown.setKey(QKeySequence(Qt.Key_Down)) self._shortcutDown.setContext(Qt.WidgetShortcut) def _restoreSelection(self): self.namesList.setCurrentRow(self.model.selected_index) #--- Event Handlers def returnPressed(self): self.model.go() def searchChanged(self): self.model.search_query = str(self.searchEdit.text()) def currentRowChanged(self, row): if row >= 0: self.model.selected_index = row def itemDoubleClicked(self, item): self.model.go() def upPressed(self): if self.namesList.currentRow() > 0: self.namesList.setCurrentRow(self.namesList.currentRow()-1) def downPressed(self): if self.namesList.currentRow() < self.namesList.count()-1: self.namesList.setCurrentRow(self.namesList.currentRow()+1) #--- model --> view def refresh(self): self.namesList.clear() self.namesList.addItems(self.model.names) self._restoreSelection() self.searchEdit.setText(self.model.search_query) def show(self): QWidget.show(self) self.searchEdit.setFocus() # see csv_options self.raise_() def hide(self): QWidget.hide(self)
def setupTab6(self, tab): """Advance widgets for preview panel""" container = QHBoxLayout() scrollArea = QScrollArea() scrollArea.setWidgetResizable(True) w = QWidget() w.setMinimumSize(QSize(400, 500)) layout = QVBoxLayout() w.setLayout(layout) scrollArea.setWidget(w) container.addWidget(scrollArea) tab.setLayout(container) # List lay = QHBoxLayout() layout.addLayout(lay) list1 = QListWidget() list1.addItems(["aaa", "bbb", "ccc"]) list2 = QListWidget() list2.addItem( QListWidgetItem(QIcon(":appres.img/Flag_blueHS.png"), "blue")) list2.addItem( QListWidgetItem(QIcon(":appres.img/Flag_redHS.png"), "red")) list2.addItem( QListWidgetItem(QIcon(":appres.img/Flag_greenHS.png"), "green")) list2.setViewMode(QListWidget.IconMode) lay.addWidget(list1) lay.addWidget(list2) # Table lay = QHBoxLayout() layout.addLayout(lay) t1 = QTableWidget() t1.setRowCount(3) t1.setColumnCount(3) for i in range(3): for j in range(3): t1.setItem(i, j, QTableWidgetItem(str((i + 1) * (j + 1)))) t1.item(i, j).setTextAlignment(Qt.AlignCenter) t1.setColumnWidth(0, 50) t1.setColumnWidth(1, 50) t1.setColumnWidth(2, 50) t1.setEditTriggers(QTableWidget.AllEditTriggers) t2 = QTableWidget() t2.setRowCount(3) t2.setColumnCount(3) t2.setHorizontalHeaderLabels(["Name", "Gender", "Age"]) t2.setVerticalHeaderLabels(["1st", "2rd", "3th"]) t2.setItem(0, 0, QTableWidgetItem("july")) c = QComboBox() c.addItems(["Male", "Famale"]) t2.setCellWidget(0, 1, c) t2.cellWidget(0, 1).setCurrentIndex(1) t2.setItem(0, 2, QTableWidgetItem("10")) t2.setItem(1, 0, QTableWidgetItem("john")) c = QComboBox() c.addItems(["Male", "Famale"]) c.setEditable(True) t2.setCellWidget(1, 1, c) t2.setItem(1, 2, QTableWidgetItem("11")) t2.resizeColumnsToContents() t2.setEditTriggers(QTableWidget.EditKeyPressed | QTableWidget.SelectedClicked | QTableWidget.AnyKeyPressed | QTableWidget.DoubleClicked) lay.addWidget(t1) lay.addWidget(t2) # Tree lay = QHBoxLayout() layout.addLayout(lay) tree1 = QTreeWidget() tree1.setColumnCount(2) tree1.setHeaderLabels(["Key", "Value"]) node1 = QTreeWidgetItem() node1.setText(0, "root") node1.setText(1, "0") node1.setIcon(0, QIcon(":appres.img/home.png")) tree1.addTopLevelItem(node1) node11 = QTreeWidgetItem() node11.setText(0, "child1") icon = QIcon(":appres.img/book_angle.png") icon.addPixmap(QPixmap(":appres.img/book_open.png"), QIcon.Normal, QIcon.On) node11.setIcon(0, icon) nodea = QTreeWidgetItem() nodea.setText(0, "red") nodea.setBackground(1, QBrush(Qt.red)) nodeb = QTreeWidgetItem() nodeb.setText(0, "gray") nodeb.setBackground(1, QBrush(Qt.gray)) nodec = QTreeWidgetItem() nodec.setText(0, "green") nodec.setBackground(1, QBrush(Qt.green)) node11.addChildren([nodea, nodeb, nodec]) node12 = QTreeWidgetItem() node12.setText(0, "child2") node12.setText(1, "child2") node13 = QTreeWidgetItem() node13.setText(0, "child3") node13.setText(1, "child3") node12.setIcon(0, icon) node13.setIcon(0, icon) node1.addChild(node11) node1.addChild(node12) node1.addChild(node13) tree1.expand(tree1.model().index(0, 0)) tree1.expandItem(node11) tree2 = QTreeView() folder = QDirModel() tree2.setModel(folder) lay.addWidget(tree1) lay.addWidget(tree2)
class ListEdit(QWidget): """A widget to edit a list of items (e.g. a list of directories).""" # emitted when anything changed in the listbox. changed = pyqtSignal() def __init__(self, *args, **kwargs): QWidget.__init__(self, *args, **kwargs) layout = QGridLayout(self) self.setLayout(layout) self.addButton = QPushButton(icons.get('list-add'), '') self.editButton = QPushButton(icons.get('document-edit'), '') self.removeButton = QPushButton(icons.get('list-remove'), '') self.listBox = QListWidget() layout.setContentsMargins(1, 1, 1, 1) layout.setSpacing(0) layout.addWidget(self.listBox, 0, 0, 8, 1) layout.addWidget(self.addButton, 0, 1) layout.addWidget(self.editButton, 1, 1) layout.addWidget(self.removeButton, 2, 1) @self.addButton.clicked.connect def addClicked(): item = self.createItem() if self.openEditor(item): self.addItem(item) @self.editButton.clicked.connect def editClicked(): item = self.listBox.currentItem() item and self.editItem(item) @self.removeButton.clicked.connect def removeClicked(): item = self.listBox.currentItem() if item: self.removeItem(item) @self.listBox.itemDoubleClicked.connect def itemDoubleClicked(item): item and self.editItem(item) self.listBox.model().layoutChanged.connect(self.changed) def updateSelection(): selected = bool(self.listBox.currentItem()) self.editButton.setEnabled(selected) self.removeButton.setEnabled(selected) self.changed.connect(updateSelection) self.listBox.itemSelectionChanged.connect(updateSelection) updateSelection() app.translateUI(self) def translateUI(self): self.addButton.setText(_("&Add...")) self.editButton.setText(_("&Edit...")) self.removeButton.setText(_("&Remove")) def createItem(self): return QListWidgetItem() def addItem(self, item): self.listBox.addItem(item) self.itemChanged(item) self.changed.emit() def removeItem(self, item): self.listBox.takeItem(self.listBox.row(item)) self.changed.emit() def editItem(self, item): if self.openEditor(item): self.itemChanged(item) self.changed.emit() def setCurrentItem(self, item): self.listBox.setCurrentItem(item) def setCurrentRow(self, row): self.listBox.setCurrentRow(row) def openEditor(self, item): """Opens an editor (dialog) for the item. Returns True if the dialog was accepted and the item edited. Returns False if the dialog was cancelled (the item must be left unedited). """ pass def itemChanged(self, item): """Called after an item has been added or edited. Re-implement to do something at this moment if needed, e.g. alter the text or display of other items. """ pass def setValue(self, strings): """Sets the listbox to a list of strings.""" self.listBox.clear() self.listBox.addItems(strings) self.changed.emit() def value(self): """Returns the list of paths in the listbox.""" return [self.listBox.item(i).text() for i in range(self.listBox.count())] def setItems(self, items): """Sets the listbox to a list of items.""" self.listBox.clear() for item in items: self.listBox.addItem(item) self.itemChanged(item) self.changed.emit() def items(self): """Returns the list of items in the listbox.""" return [self.listBox.item(i) for i in range(self.listBox.count())] def clear(self): """Clears the listbox.""" self.listBox.clear() self.changed.emit()
class StringListDlg(QDialog): """docstring for Form""" def __init__(self, title="Title", items=[]): super(StringListDlg, self).__init__() self.initUi(title, items) def initUi(self, title, items): layout = QGridLayout() self.qlist = QListWidget() self.stringlist = items if len(self.stringlist) == 0: self.feedList() else: self.qlist.addItems(self.stringlist) layout.addWidget(self.qlist, 0, 0, 7, 3) butttonsList = [ '&Add...', '&Edit...', '&Remove...', '&Up', '&Down', '&Sort', '&Close' ] for idx, button in enumerate(butttonsList): qPushButton = QPushButton() method = str.lower((button.split('.')[0])[1:]) qPushButton.clicked.connect(getattr(self, method)) qPushButton.setText(button) layout.addWidget(qPushButton, idx, 3) self.setLayout(layout) self.setWindowTitle('List of %s' % title) self.show() def feedList(self): for x in range(10): self.stringlist.append("List item number %.3d" % (random.randrange(100))) @pyqtSlot() def add(self): print('add') text, okPressed = QInputDialog.getText(self, "Add Item", "New Item:", QLineEdit.Normal, "") if okPressed and text != '': self.stringlist.append(text) self.qlist.clear() self.qlist.addItems(self.stringlist) self.qlist.scrollToBottom() @pyqtSlot() def edit(self): print('edit') text, okPressed = QInputDialog.getText(self, "Add Item", "New Item:", QLineEdit.Normal, self.qlist.currentItem().text()) if okPressed and text != '': self.qlist.currentItem().setText(text) @pyqtSlot() def remove(self): print('remove') self.qlist.takeItem(self.qlist.currentRow()) @pyqtSlot() def up(self): print('up') if self.qlist.currentRow() > 0: item = self.qlist.takeItem(self.qlist.currentRow()) self.qlist.insertItem((self.qlist.currentRow() - 1), item.text()) self.qlist.setCurrentRow((self.qlist.currentRow() - 2)) @pyqtSlot() def down(self): print('down') if self.qlist.currentRow() < self.qlist.count(): item = self.qlist.takeItem(self.qlist.currentRow()) self.qlist.insertItem((self.qlist.currentRow() + 1), item.text()) self.qlist.setCurrentRow((self.qlist.currentRow() + 1)) @pyqtSlot() def sort(self): print('sort') self.qlist.sortItems() self.qlist.scrollToTop() @pyqtSlot() def close(self): print('close') self.stringlist = [] for i in range(0, self.qlist.count()): self.stringlist.append(self.qlist.item(i).text()) self.accept()