def __init__(self, parent=None): # Initialize window QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Initialize search list (on left) self.lstSearch = self.ui.lstSearch self.modelSearch = QtGui.QStandardItemModel(self.lstSearch) # Initialize similar list (on right) self.lstSimilar = self.ui.lstSimilar self.modelSimilar = QtGui.QStandardItemModel(self.lstSimilar) # Define functions for buttons self.ui.btnDone.clicked.connect(self.popupwindow) self.ui.btnSearch.clicked.connect(self.search) self.ui.btnAdd.clicked.connect(self.add) self.ui.btnRem.clicked.connect(self.rem) self.ui.actionEdit_info.triggered.connect(self.edit) # Defualt db info self.host = 'localhost' self.db = '' self.usr = '******' self.pw = '' # Lists used to store ratings and years self.moviesselected = [] self.movieyears = [] self.movieratings = [] self.tmpmovieyears = [] self.tmpmovieratings = []
def __init__(self): super().__init__() self.plot_speeds = False self.bessel = Bessel() self.speeds = Speeds(self.bessel) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.besselCanvas = BesselGraph(self, width=5, height=4, bessel=self.bessel) self.ui.besselGraphLayout.addWidget(self.besselCanvas) self.speedsCanvas = SpeedsCanvas(self, width=5, height=4, speeds=self.speeds) self.ui.speedsGraphLayout.addWidget(self.speedsCanvas) self.show() self.ui.besselPlotButton.clicked.connect(self.besselCanvas.plot) self.besselCanvas.got_results.connect(self.update_bessel_results) self.ui.coefSpinBox.valueChanged.connect(self.update_bessel_params) self.ui.radiusSpinBox.valueChanged.connect(self.update_bessel_params) self.ui.epsSpinBox.valueChanged.connect(self.update_bessel_params) self.ui.precisionSpinBox.valueChanged.connect( self.update_bessel_params) self.ui.besselPlotButton.clicked.connect(self.speedsCanvas.plot)
def __init__(self): super(myapp, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.process = QProcess(self) self.ui.pushButton.clicked.connect(self.btnClicked) self.ui.pushButton_2.clicked.connect(self.process.kill)
class MyApp(QtWidgets.QMainWindow): def __init__(self, parent=None): super(MyApp, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.process = QtCore.QProcess(self) self.ui.pushButton.clicked.connect(self.start_process) self.ui.pushButton_2.clicked.connect(self.stop_process) self._pid = -1 @QtCore.pyqtSlot() def start_process(self): runstr = "ping" args = ["localhost", "-t"] self.process.setProgram(runstr) self.process.setArguments(args) ok, pid = self.process.startDetached() if ok: self._pid = pid @QtCore.pyqtSlot() def stop_process(self): if self._pid > 0: p = psutil.Process(self._pid) p.terminate() self._pid = -1
class MyDialog(QtWidgets.QMainWindow): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.model = QtGui.QStandardItemModel(self) #tablesettings and so stuf self.doGuiPostInit() def doGuiPostInit(self): self.ui.tableView.setModel(self.model) self.ui.actionImport.triggered.connect(self.opnfil) #self.ui.actionImport.triggered. #self.ui.actionImport.clicked.connect(self.opnfil()) #self.opnfil() def opnfil(self): filename = QtWidgets.QFileDialog.getOpenFileName(None, 'Open ', '/home')[0] self.readAndInsertCSV(filename) def readAndInsertCSV(self, filename): with open(filename, "r") as filein: for row in csv.reader(filein): items = [ QtGui.QStandardItem(field) for field in row ] self.model.appendRow(items)
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.worker = Worker() self.worker.update.connect(self.updateTime) self.worker.finish.connect(self.finish)
class Masin(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.signals() self.gci = Gcinvoice() def gnuCashClick(self): filename = QtGui.QFileDialog.getOpenFileName(self, 'Choose File', '.') self.ui.gnuCashEditline.setText(filename) def latexTemplateClick(self): filename = QtGui.QFileDialog.getOpenFileName(self, 'Choose File', '.') self.ui.latexTemplateEditline.setText(filename) def outputFilenameClick(self): filename = QtGui.QFileDialog.getOpenFileName(self, 'Create File', '.') self.ui.outputFilenameEditline.setText(filename) def signals(self): QtCore.QObject.connect(self.ui.gnuCashButton, QtCore.SIGNAL("clicked()"), self.gnuCashClick) QtCore.QObject.connect(self.ui.latexTemplateButton, QtCore.SIGNAL("clicked()"), self.latexTemplateClick) QtCore.QObject.connect(self.ui.outputFilenameButton, QtCore.SIGNAL("clicked()"), self.outputFilenameClick) QtCore.QObject.connect(self.ui.generateButton, QtCore.SIGNAL("clicked()"), self.generateClick) def generateClick(self): self.gci.parse(str(self.ui.gnuCashEditline.text())) self.gci.createInvoice(invoiceid=str(self.ui.invoiceNumberSpinbox.text()), template=str(self.ui.latexTemplateEditline.text()), outfile=str(self.ui.outputFilenameEditline.text())) print "done"
def __init__(self): super(ApplicationWindow, self).__init__() self.inited = False self.ui = Ui_MainWindow() self.ui.setupUi(self) try: with open('style.qss', 'r', encoding='utf-8') as f: self.setStyleSheet(f.read()) except: pass bind_host, bind_port = qt_get_host_port(self, '0.0.0.0', 22321) if bind_host is None or bind_port is None: return self.user = User(bind_host, bind_port, 'MagHSK') self.serverModel = ListTableModel(['uuid', 'host', 'port']) self.ui.serverTable.setModel(self.serverModel) self.blogModel = ListTableModel(['date', 'id', 'text']) self.ui.blogTable.setModel(self.blogModel) self.ui.refreshBlogButton.clicked.connect(self.refreshBlogButtonAction) self.ui.detailButton.clicked.connect(self.detailButtonAction) self.ui.subscribeButton.clicked.connect(self.subscribeButtonAction) self.ui.unsubscribeButton.clicked.connect(self.unsubscribeButtonAction) self.ui.updateButton.clicked.connect(self.updateButtonAction) self.ui.keywordButton.clicked.connect(self.keywordButtonAction) self.ui.refreshServerButton.clicked.connect( self.refreshServerButtonAction) self.ui.clearButton.clicked.connect(self.clearButtonAction) self.select_server = None self.select_blog = None self.client_thread = ClientThread(self) self.client_thread.serverUpdated.connect(self.refreshServer) self.client_thread.blogUpdated.connect(self.refreshBlog) self.client_thread.start() self.inited = True
def __init__(self, parent=None): super(MyApp, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.process = QtCore.QProcess(self) self.ui.pushButton.clicked.connect(self.start_process) self.ui.pushButton_2.clicked.connect(self.stop_process) self._pid = -1
def __init__(self): self.im = None self.app = QApplication(sys.argv) self.Form = QWidget() self.ui = Ui_MainWindow() self.ui.setupUi(self.Form) self.ui.b_open.clicked.connect(self.b_open_clicked) self.ui.b_filter.clicked.connect(self.b_filter_clicked) self.v = variables()
def __init__(self): super(mywindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.createConnection() # Запуск метода создания подключения к Бд self.createMainMenu() # Запуск метода для создания главного меню # привязка клика на кнопку к Методу(для запуска второго окна) self.ui.pushButton.clicked.connect(self.btnClicked)
class AppWindow(QMainWindow): def __init__(self): super().__init__() self.plot_speeds = False self.bessel = Bessel() self.speeds = Speeds(self.bessel) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.besselCanvas = BesselGraph(self, width=5, height=4, bessel=self.bessel) self.ui.besselGraphLayout.addWidget(self.besselCanvas) self.speedsCanvas = SpeedsCanvas(self, width=5, height=4, speeds=self.speeds) self.ui.speedsGraphLayout.addWidget(self.speedsCanvas) self.show() self.ui.besselPlotButton.clicked.connect(self.besselCanvas.plot) self.besselCanvas.got_results.connect(self.update_bessel_results) self.ui.coefSpinBox.valueChanged.connect(self.update_bessel_params) self.ui.radiusSpinBox.valueChanged.connect(self.update_bessel_params) self.ui.epsSpinBox.valueChanged.connect(self.update_bessel_params) self.ui.precisionSpinBox.valueChanged.connect( self.update_bessel_params) self.ui.besselPlotButton.clicked.connect(self.speedsCanvas.plot) def update_bessel_results(self, results): self.ui.besselResultsEdit.setText(results) def update_bessel_params(self): try: eps = self.ui.epsSpinBox.value() R = self.ui.radiusSpinBox.value() k = self.ui.coefSpinBox.value() precision = self.ui.precisionSpinBox.value() self.bessel.set_params(eps, R, k, precision) if self.ui.autoUpdateCheckBox.isChecked(): self.ui.besselPlotButton.clicked.emit() print(eps, R, k) except (ValueError, TypeError): print("Bad value") @staticmethod def error_message(message, title): box = QMessageBox() box.setIcon(QMessageBox.Warning) box.setText(message) box.setWindowTitle(title) box.exec_()
def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) # initialise auxiliary class self.data = dataFiles.DataFiles() self.lineEditWorkingFolder.setText(os.getcwd()) self.updateCurrentWorkingFolder() # About self.popDialog=myDialog()
class mywindow(QtWidgets.QMainWindow): def __init__(self): super(mywindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.editenv = editEnv(self.ui.QtreeDirs, self.ui.qtreeJson, self.ui.update_btn, self.ui.saveFile_btn, self.ui.reload_btn, 'json_files') #self.ui.plainTextEdit.setPlainText(json.dumps(self.editenv.dirfiletree.tree)) def wheelEvent(self,event): ve.testDrawing(self.ui.graphicsView)
def __init__(self): super(Window, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.startButton.clicked.connect(self.btn_start_clicked) self.ui.barGraph.clicked.connect(self.btn_bar_graph_clicked) self.ui.correlation.clicked.connect(self.btn_correlation_clicked) self.ui.scatter.clicked.connect(self.btn_scatter_clicked) self.ui.barGraph_2.clicked.connect(self.btn_bar_graph_2_clicked) self.ui.correlation_2.clicked.connect(self.btn_correlation_2_clicked) self.ui.scatter_2.clicked.connect(self.btn_scatter_2_clicked) self.ui.radioButtonTask.toggled.connect(self.change_radio_btn) self.ui.radioButtonTask.toggled.connect(self.change_radio_btn) self.ui.pushButton_2.clicked.connect(self.plots) self.ui.pushButton_3.clicked.connect(self.avr_plots) self.ui.pushButton.clicked.connect(self.coefficient_plots)
def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.model = QtGui.QStandardItemModel(self) #tablesettings and so stuf self.doGuiPostInit()
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.centralWidget.setLayout(self.ui.mainLayout) self.ui.critLabel = QtGui.QLabel() self.ui.statusbar.addPermanentWidget(self.ui.critLabel) self.edit_dialog = EditDialog(self) self.result_dialog = ResultDialog(self) #Вызовы диалогов self.connect(self.ui.resultAction, SIGNAL('activated()'), self.show_result_slot) self.connect(self.ui.editAction, SIGNAL('activated()'), self.data_edit_slot) #Принятие изменений self.connect(self.ui.applyChanges, SIGNAL('activated()'), self.change_data_slot) self.connect(self.edit_dialog.ui.applyButton, SIGNAL('clicked()'), self.apply_new_data_slot) self.graph = NetGraph() self.start_works = deepcopy(self.graph.works) self.fill_tables() self.results = [] self.update_results()
def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.createDatabase() self.showInfo() self.ui.pushButton_AddPatient.clicked.connect(self.add) self.ui.pushButton_AddPatient.clicked.connect(self.clearLine) self.ui.pushButton_DeletePatient.clicked.connect(self.deleteinfo) self.ui.pushButton.clicked.connect( lambda: self.search(self.ui.lineEdit.text())) self.ui.pushButton_ShowPAtient.clicked.connect(self.showall) self.show()
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.signals() self.gci = Gcinvoice()
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.cb_impressoras.addItems(listar_porta_serial()) self.ui.btn_conectar.clicked.connect(self.clicar_btn_conectar) self.ui.btn_imprimir_texto.clicked.connect( self.clicar_btn_imprimir_texto) self.ui.btn_imprimir_qr_code.clicked.connect( self.clicar_btn_imprimir_qr_code) self.ui.btn_buscar_imagem.clicked.connect( self.clicar_btn_buscar_imagem) self.ui.btn_imprimir_imagem.clicked.connect( self.clicar_btn_imprimir_imagem) self.impressao = None self.status_impressao = False
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.centralWidget.setLayout(self.ui.plotArea) self.plot = Oscillator(self.ui.centralWidget) self.ui.plotArea.addWidget(self.plot) self.const_dialog = ConstDialog(self) self.set_dialog_const() self.connect(self.ui.constEditAction, SIGNAL('activated()'), self.edit_constant_slot) self.connect(self.ui.calculateAction, SIGNAL('activated()'), self.draw_plot_slot) self.connect(self.ui.saveImageAction, SIGNAL('activated()'), self.save_plot_image_slot) self.connect(self.const_dialog.ui.applyButton, SIGNAL('clicked()'), self.apply_const_slot) self.connect(self.const_dialog.ui.resetButton, SIGNAL('clicked()'), self.reset_const_slot)
class App(QtWidgets.QMainWindow): def __init__(self): super(App, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.df = pd.read_csv("worldometer_data.csv") def Country(self): Countrys = self.df["Country/Region"] for i in Countrys: self.ui.comboBox.addItem(i) self.ui.pushButton.clicked.connect(self.on_clicked) def on_clicked(self): MyCountry = self.ui.comboBox.currentText() MC = self.df[self.df["Country/Region"] == MyCountry]["TotalDeaths"].iloc[0] MyCountry = str(int(MC)) self.ui.label_2.setText(MyCountry)
class main: def __init__(self): self.im = None self.app = QApplication(sys.argv) self.Form = QWidget() self.ui = Ui_MainWindow() self.ui.setupUi(self.Form) self.ui.b_open.clicked.connect(self.b_open_clicked) self.ui.b_filter.clicked.connect(self.b_filter_clicked) self.v = variables() def b_open_clicked(self): filename = QFileDialog.getOpenFileName( caption="Открыть изображение", filter="Файлы изображений (*.jpg)") if filename != ('', ''): self.im = image(filename[0]) self.output_image(self.im, 1) def b_filter_clicked(self): if (self.im == None): QMessageBox.critical(QWidget(), 'Ошибка', "Изображение для обработки не выбрано") return im2 = self.im.filter( self.v.get_filter_code(name=self.ui.cb_filter.currentText())) im2 = self.im.filter("INF") im2 = self.im.filter("IVF") im2 = self.im.filter("BNF") im2 = self.im.filter("BVF") im2 = self.im.filter("GNF") im2 = self.im.filter("GVF") #self.output_image(im2, 2) def output_image(self, im, num): if (num == 1): self.ui.label1.setPixmap(im.to_qpixmap()) if (num == 2): self.ui.label2.setPixmap(im.to_qpixmap()) def main(self): self.Form.show() sys.exit(self.app.exec_())
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.worker = Worker() self.worker.update.connect(self.updateTime) self.worker.finish.connect(self.finish) def onStart(self): jobs = [] for i in range(10): jobs.append(i) self.worker.start() def updateTime(self, seconds): self.ui.lblSeconds.setText(str(seconds)) def finish(self): self.ui.btnStart.setText('Finish') self.ui.btnStart.setEnabled(False)
class myapp(QtWidgets.QMainWindow): def __init__(self): super(myapp, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.process = QProcess(self) self.ui.pushButton.clicked.connect(self.btnClicked) self.ui.pushButton_2.clicked.connect(self.process.kill) def btnClicked(self): #os.system('python script.py') #os.spawnl(os.P_NOWAIT, 'python script.py') #proc = subprocess.Popen(['python','script.py']) #tr = TestThreading() #time.sleep(1) #print(datetime.datetime.now().__str__() + ' : First output') #time.sleep(2) #print(datetime.datetime.now().__str__() + ' : Second output') #thread = threading.Thread(target=self.run, args=()) runstr = 'ping' args = ['localhost', '-t'] #self.process.finished.connect(self.onFinished) #self.process.start(runstr, args) self.process.setStandardOutputFile( 'C:\Learning\PythonLearning2\BackgroundRun\ping.log') self.process.start(runstr, args) #self.process.waitForFinished() #result = self.process.readAll() #self.process.close() def onFinished(self, exitCode, exitStatus): pass def run(self): while True: # More statements comes here print(datetime.datetime.now().__str__() + ' : Start task in the background') time.sleep(self.interval)
def __init__(self, parent=None): # Initialize window QtGui.QWidget.__init__(self,parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Initialize search list (on left) self.lstSearch = self.ui.lstSearch self.modelSearch = QtGui.QStandardItemModel(self.lstSearch) # Initialize similar list (on right) self.lstSimilar = self.ui.lstSimilar self.modelSimilar = QtGui.QStandardItemModel(self.lstSimilar) # Define functions for buttons self.ui.btnDone.clicked.connect(self.close) self.ui.btnSearch.clicked.connect(self.search) self.ui.btnAdd.clicked.connect(self.add) self.ui.btnRem.clicked.connect(self.rem) # KeyEvent filter to filter out when you press the return key self.ui.searchtext.installEventFilter(self)
def __init__(self, parent = None): super(QTR, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.fileDialog = QtGui.QFileDialog(self) self.qcut = DesignerMainWindow(parent = self) #self.qcut.show() # Відкат даних із QCut self.qcut.dataChanged.connect(self.getBackFromQcut) #self.qcut.show() self.intensDialog = IntensDialog() self.calibrDialog = CalibrDialog(self.Root) self.ui.tab_2.setEnabled(False) self.ui.tab_3.setEnabled(False) self.ui.tab_4.setEnabled(False) QtGui.QShortcut(QtGui.QKeySequence("Ctrl+Q"), self, self.close) ##### Signals -> Slots ######################################### self.uiConnect()
def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.run_button_.clicked.connect(self.loadRegExp)
class GraphApplication(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.centralWidget.setLayout(self.ui.mainLayout) self.ui.critLabel = QtGui.QLabel() self.ui.statusbar.addPermanentWidget(self.ui.critLabel) self.edit_dialog = EditDialog(self) self.result_dialog = ResultDialog(self) #Вызовы диалогов self.connect(self.ui.resultAction, SIGNAL('activated()'), self.show_result_slot) self.connect(self.ui.editAction, SIGNAL('activated()'), self.data_edit_slot) #Принятие изменений self.connect(self.ui.applyChanges, SIGNAL('activated()'), self.change_data_slot) self.connect(self.edit_dialog.ui.applyButton, SIGNAL('clicked()'), self.apply_new_data_slot) self.graph = NetGraph() self.start_works = deepcopy(self.graph.works) self.fill_tables() self.results = [] self.update_results() def fill_tables(self, previous_workers='', previous_details='', previous_crit_length=''): """Внесение данных в таблицы""" works = self.graph.get_works() #states = self.graph.get_states() self.fill_works_table(works) #self.fill_states_tables(states) self.crit_path = self.graph.get_crit_path() self.crit_path_length = self.graph.get_crit_path_length() self.workers_count = self.graph.get_workers_count() self.details_count = self.graph.get_details_count() status_bar_values = (self.workers_count, previous_workers, self.details_count, previous_details, self.crit_path, self.crit_path_length, previous_crit_length) status_bar_string = u'Рабочих = %s %s, Деталей = %s %s Критический путь = %s Длина критического пути = %.9f %s' self.ui.critLabel.setText(status_bar_string % status_bar_values) def fill_works_table(self, works): """Заполнение таблицы работ""" self.ui.worksTable.setRowCount(len(works)) table_columns = {'start': 0, 'end': 1, 'details': 2, 'workers': 3, 'duration': 4, 'full_reserv': 5} for i in range(0, len(works)): for key in works[i].keys(): item = QtGui.QTableWidgetItem('%s' % abs(works[i][key])) self.ui.worksTable.setItem(i, table_columns[key], item) def fill_states_tables(self, states): """Заполнение таблицы состояний""" self.ui.statesTable.setRowCount(len(states)) table_columns = {'num': 0, 'soon_end': 1, 'late_end': 2, 'reserv': 3} for i in range(0, len(states)): for key in states[i].keys(): item = QtGui.QTableWidgetItem('%s' % abs(states[i][key])) self.ui.statesTable.setItem(i, table_columns[key], item) def update_results(self, generations=0): """Добавляет очередной шаг расчетов в таблицу результатов""" works = self.graph.get_works() workers = [] result ={} for work in works: workers.append(work['workers']) result['workers'] = workers result['crit_path'] = str(self.crit_path) result['crit_length'] = self.crit_path_length result['generations'] = generations self.results.append(result) """============================== Слоты =====================================""" def show_result_slot(self): rd = self.result_dialog works = self.graph.get_works() result_text = u'' result_text += u'Производительность = %s<br /><br />' % self.graph.productivity result_text += u'Начальные данные:' result_text += u'<table border="1" cellpadding="5" cellspacing="0">' result_text += u'<tr><td>Начало</td>\ <td>Конец</td>\ <td>Деталей</td>\ <td>Рабочих</td>\ <td>Длительностьр работ</td>\ </tr>' for work in works: result_text += u'<tr>' result_text += u'<td>%s</td>' % work['start'] result_text += u'<td>%s</td>' % work['end'] result_text += u'<td>%s</td>' % work['details'] result_text += u'<td>%s</td>' % work['workers'] result_text += u'<td>%s</td>' % work['duration'] result_text += u'</tr>' result_text += u'</table>' result_text += u'<br /><br />' result_text += u'Резервы работ:' result_text += u'<table border="1" cellpadding="5" cellspacing="0">' result_text += u'<tr><td>Работа</td>\ <td>Резерв</td>\ </tr>' for work in works: result_text += u'<tr>' result_text += u'<td>%s-%s</td>' % (work['start'], work['end']) result_text += u'<td>%s</td>' % work['full_reserv'] result_text += u'</tr>' result_text += u'</table>' result_text += u'<br /><br />' result_text += u'Резервы событий:' result_text += u'<table border="1" cellpadding="5" cellspacing="0">' result_text += u'<tr><td>Событие</td>\ <td>Резерв</td>\ </tr>' states = self.graph.get_states() for state in states: result_text += u'<tr>' result_text += u'<td>%s</td>' % state['num'] result_text += u'<td>%s</td>' % state['reserv'] result_text += u'</tr>' result_text += u'</table>' result_text += u'<br /><br />' rd.ui.dataText.setText(result_text) result_text = u'' result_text += u'Расчеты:' result_text += u'<table border="1" cellpadding="5" cellspacing="0">' result_text += u'<tr><td colspan="%s">Распределение рабочих по работам</td><td colspan="4">Параметры</td></tr>' % len(works) result_text += u'<tr style="font-weight: bold">' for work in works: result_text += u'<td>%s-%s</td>' % (work['start'], work['end']) result_text += u'<td>Всего рабочих</td>' result_text += u'<td>Крит. путь</td>' result_text += u'<td>Длина крит. пути</td>' result_text += u'<td>Поколений ГА</td>' result_text += u'</tr>' for result in self.results: result_text += u'<tr>' workers_count = 0 for workers in result['workers']: workers_count += workers result_text += u'<td>%s</d>' % workers result_text += u'<td>%s</td>' % workers_count result_text += u'<td>%s</td>' % result['crit_path'] result_text += u'<td>%s</td>' % result['crit_length'] result_text += u'<td>%s</td>' % result['generations'] result_text += u'</tr>' result_text += u'</table>' rd.ui.calculationsText.setText(result_text) rd.show() def data_edit_slot(self): """Вызов окна редактирования количества рабочих, деталей и продуктивности""" works = self.graph.get_works() table_columns = {'start': 0, 'end': 1, 'details': 2, 'workers': 3} dt = self.edit_dialog.ui.dataTable dt.setRowCount(len(works)) for i in range(0, len(works)): for key in table_columns.keys(): item = QtGui.QTableWidgetItem('%s' % abs(works[i][key])) dt.setItem(i, table_columns[key], item) self.edit_dialog.ui.productivity.setValue(self.graph.productivity) self.edit_dialog.show() def apply_new_data_slot(self): """Расчет графа для новых данных, введенных в диалоге редактирования""" del(self.results[:]) table_columns = {'start': 0, 'end': 1, 'details': 2, 'workers': 3} dt = self.edit_dialog.ui.dataTable works = [] for i in range(0, dt.rowCount()): work = {} for key in table_columns.keys(): item = dt.item(i, table_columns[key]) work[key] = int(item.text()) works.append(work) self.graph.productivity = self.edit_dialog.ui.productivity.value() self.graph.works = works self.graph.calculate_graph() self.fill_tables() self.update_results() def change_data_slot(self): """Пересчет""" self.graph.works = deepcopy(self.start_works) self.graph.calculate_graph() populations = self.ui.populationBox.value() mutation_coef = self.ui.mutationBox.value() survival_coef = self.ui.survivalBox.value() generations_count = self.graph.evolute(population_size=populations, mutation=mutation_coef, survival=survival_coef) self.fill_tables('(%s)' % self.workers_count, '(%s)' % self.details_count, '(%s)' % self.crit_path_length) self.update_results(generations=generations_count)
class MyDialog(QtGui.QMainWindow): def __init__(self, parent=None): # Initialize window QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Initialize search list (on left) self.lstSearch = self.ui.lstSearch self.modelSearch = QtGui.QStandardItemModel(self.lstSearch) # Initialize similar list (on right) self.lstSimilar = self.ui.lstSimilar self.modelSimilar = QtGui.QStandardItemModel(self.lstSimilar) # Define functions for buttons self.ui.btnDone.clicked.connect(self.popupwindow) self.ui.btnSearch.clicked.connect(self.search) self.ui.btnAdd.clicked.connect(self.add) self.ui.btnRem.clicked.connect(self.rem) self.ui.actionEdit_info.triggered.connect(self.edit) # Defualt db info self.host = 'localhost' self.db = '' self.usr = '******' self.pw = '' # Lists used to store ratings and years self.moviesselected = [] self.movieyears = [] self.movieratings = [] self.tmpmovieyears = [] self.tmpmovieratings = [] ######################### Open dialog for editing database info ######################### def edit(self): self.wedit = DBInfo(self) self.wedit.setStyleSheet( qdarkstyle.load_stylesheet()) # For dark theme self.wedit.show() ######################### Go into the database and get searched movies ######################### def getdat(self, inputdata): ######################### Connect to database ######################### try: conn_string = "host='{}' dbname='{}' user='******' password='******'".format( self.host, self.db, self.usr, self.pw) conn = psycopg2.connect(conn_string) cursor = conn.cursor() except: errorstr = 'You are not connected to a database, \n\n press CTRL + E to access database settings' QtGui.QMessageBox.information(self, 'Error', errorstr) ######################### Create sql command ######################### s = """select title, year, rating from movies where lower(title) like %s or year like %s order by title;""" values = ('%' + inputdata.replace("'", "''").lower() + '%', '%' + inputdata.replace("'", "''") + '%') ######################### Get movies from search ######################### cursor.execute(s, values) retval = cursor.fetchall() cursor.close() conn.close() return retval def search(self): ######################### Clear listbox and tmpmovieyears ######################### self.modelSearch.clear() self.tmpmovieyears.clear() self.tmpmovieratings.clear() ######################### Get text from textbox and clear it ######################### txt = self.ui.searchtext.text() self.ui.searchtext.clear() ######################### Get data from sql database ######################### movielistoftuple = self.getdat(txt) ######################### Add items to list ######################### for i in movielistoftuple: # Get each line of text self.tmpmovieyears.append(i[1]) self.tmpmovieratings.append(i[2]) txt = i[0] # Create item from text and add to list item = QtGui.QStandardItem(txt) item.setEditable(False) #Add to the list self.modelSearch.appendRow(item) ######################### Make sure list appears ######################### self.lstSearch.setModel(self.modelSearch) def add(self): ######################### Get index for selected item ######################### index = self.lstSearch.selectedIndexes()[0] ######################### Get item associated with selected index ######################### item = self.modelSearch.itemFromIndex(index) newitem = QtGui.QStandardItem(item.text()) newitem.setEditable(False) ######################### Add item to list ######################### if newitem.text() not in self.moviesselected or self.tmpmovieyears[ index.row()] not in self.movieyears: # Add to the list of values selected test = self.moviesselected.append(newitem.text()) self.movieyears.append(self.tmpmovieyears[index.row()]) self.movieratings.append(self.tmpmovieratings[index.row()]) self.tmpmovieyears.pop(index.row()) self.tmpmovieratings.pop(index.row()) # Move to similar list self.modelSimilar.appendRow(newitem) self.lstSimilar.setModel(self.modelSimilar) ######################### Remove item from search list ######################### self.modelSearch.removeRow(index.row()) self.lstSearch.setModel(self.modelSearch) def rem(self): ######################### Get index for selected item ######################### index = self.lstSimilar.selectedIndexes()[0] ######################### Get item associated with selected index ######################### item = self.modelSimilar.itemFromIndex(index) newitem = QtGui.QStandardItem(item.text()) newitem.setEditable(False) ######################### Remove from the list of values selected ######################### test = self.moviesselected.remove(item.text()) ######################### Remove item from similar list ######################### self.modelSimilar.removeRow(index.row()) self.lstSimilar.setModel(self.modelSimilar) self.tmpmovieyears.append(self.movieyears[index.row()]) self.tmpmovieratings.append(self.movieratings[index.row()]) self.movieyears.pop(index.row()) self.movieratings.pop(index.row()) ######################### Move to search list ######################### self.modelSearch.appendRow(newitem) self.lstSearch.setModel(self.modelSearch) def popupwindow(self): ######################### Connect to db ######################### conn_string = "host='{}' dbname='{}' user='******' password='******'".format( self.host, self.db, self.usr, self.pw) conn = psycopg2.connect(conn_string) cursor = conn.cursor() ######################### Create sql command to get genres ######################### sqlcmd = """select distinct lower(g.genre) from genres g, movies m where m.id = g.movieid and (""" for i in range(len(self.moviesselected) - 1): sqlcmd += "lower(m.title) = '" + self.moviesselected[i].replace( "'", "''").lower( ) + "' and m.year = '" + self.movieyears[i] + "' or " sqlcmd += "lower(m.title) = '" + self.moviesselected[ len(self.moviesselected) - 1].replace( "'", "''").lower() + "' and m.year = '" + self.movieyears[len( self.moviesselected) - 1] + "') order by lower(g.genre);" ######################### Get genres ######################### cursor.execute(sqlcmd) genres = cursor.fetchall() ######################### Create sql command to get tags ######################### sqlcmd = """select distinct lower(mt.tag) from genres g, movies m, mtags mt where m.id = g.movieid and m.id = mt.movieid and (""" for i in range(len(self.moviesselected) - 1): sqlcmd += "lower(m.title) = '" + self.moviesselected[i].replace( "'", "''").lower( ) + "' and m.year = '" + self.movieyears[i] + "' or " sqlcmd += "lower(m.title) = '" + self.moviesselected[ len(self.moviesselected) - 1].replace( "'", "''").lower() + "' and m.year = '" + self.movieyears[len( self.moviesselected) - 1] + "') order by lower(mt.tag);" ######################### Get tags ######################### cursor.execute(sqlcmd) tags = cursor.fetchall() ######################### Get lowest rating from chosen movies ######################### avgminfive = sum(self.movieratings) / len(self.movieratings) - 0.5 ######################### Create sql command to get similar movies ######################### sqlcmd = """select m.title, m.year from genres g, movies m, mtags mt where m.id = g.movieid and m.id = mt.movieid and m.rating >= """ + str(avgminfive) + """ and (""" if len(genres) > 0: for i in range(len(genres) - 1): sqlcmd += "lower(g.genre) = '" + genres[i][0].replace( "'", "''") + "' or " sqlcmd += "lower(g.genre) = '" + genres[ len(genres) - 1][0].replace("'", "''") + "')\nand (" if len(tags) > 0: for i in range(len(tags) - 1): sqlcmd += "lower(mt.tag) = '" + tags[i][0].replace( "'", "''") + "' or " sqlcmd += "lower(mt.tag) = '" + tags[len(tags) - 1][0].replace( "'", "''") + "')\nand (" if len(self.moviesselected) > 0: for i in range(len(self.moviesselected) - 1): sqlcmd += "lower(m.title) != '" + self.moviesselected[ i].replace("'", "''").lower( ) + "' and m.year != '" + self.movieyears[i] + "' and " sqlcmd += "lower(m.title) != '" + self.moviesselected[len( self.moviesselected ) - 1].replace("'", "''").lower( ) + "' and m.year != '" + self.movieyears[ len(self.moviesselected) - 1] + "') group by m.title, m.year order by count(m.title) desc limit {}".format( NROFMOVIES) ######################### Sort similar movies according to rating ######################### sqlcmd = """select m.title, m.year, m.rating from movies m where (m.title, m.year) in (""" + sqlcmd + """) order by m.rating desc;""" ######################### Get similar movies ######################### cursor.execute(sqlcmd) similar = cursor.fetchall() ######################### Show movies in messagebox ######################### moviestr = 'Movies you might like:\n\n' for i in range(len(similar)): moviestr += similar[i][0] + ' (' + similar[i][1] + ')\n' moviestr += '\nWould you like to try again?' # The QWidget widget is the base class of all user interface objects in PyQt4. w = QtGui.QWidget() ######################### Show a message box ######################### result = QtGui.QMessageBox.question( w, "Movies you might like", moviestr, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) # Close application if user chooses no if result != QtGui.QMessageBox.Yes: self.close() cursor.close() conn.close()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.cb_impressoras.addItems(listar_porta_serial()) self.ui.btn_conectar.clicked.connect(self.clicar_btn_conectar) self.ui.btn_imprimir_texto.clicked.connect( self.clicar_btn_imprimir_texto) self.ui.btn_imprimir_qr_code.clicked.connect( self.clicar_btn_imprimir_qr_code) self.ui.btn_buscar_imagem.clicked.connect( self.clicar_btn_buscar_imagem) self.ui.btn_imprimir_imagem.clicked.connect( self.clicar_btn_imprimir_imagem) self.impressao = None self.status_impressao = False def clicar_btn_conectar(self): if (self.ui.btn_conectar.text() == "Conectar"): nome_serial = self.ui.cb_impressoras.currentText() if (nome_serial == ""): pass else: self.ui.btn_atualizar.setEnabled(False) self.ui.cb_impressoras.setEnabled(False) self.ui.btn_conectar.setText("Desconectar") self.impressao = Imprimir(nome_serial) self.status_impressao = True self.ui.statusbar.showMessage(nome_serial + " conectado.") elif (self.ui.btn_conectar.text() == "Desconectar"): self.ui.btn_atualizar.setEnabled(True) self.ui.cb_impressoras.setEnabled(True) self.ui.btn_conectar.setText("Conectar") self.status_impressao = False self.ui.statusbar.showMessage("Desconectado.") def clicar_btn_imprimir_texto(self): if (self.status_impressao == True): self.impressao.imprimir_texto(self.ui.ed_texto.toPlainText()) else: self.ui.statusbar.showMessage("Impressora não está conectada!") def clicar_btn_imprimir_imagem(self): if (self.status_impressao == True): if (self.ui.ed_imagem.text() == ""): pass else: self.impressao.imprimir_imagem(self.ui.ed_imagem.text()) else: self.ui.statusbar.showMessage("Impressora não está conectada!") def clicar_btn_buscar_imagem(self): imagem = QFileDialog.getOpenFileName(self, "Open Image", "", "Image Files (*.gif)") self.ui.ed_imagem.setText(str(imagem[0])) def clicar_btn_imprimir_qr_code(self): if (self.status_impressao == True): self.impressao.imprimir_qr_code(self.ui.ed_qr_code.toPlainText()) else: self.ui.statusbar.showMessage("Impressora não está conectada!")
import sys
class QTR(QtGui.QMainWindow): ''' Ініціалізація змінних. cXXXXXX - змінна, що відповідає кросу sXXXXXX - змінна, що відповідає зразку rXXXXXX - змінна, що відповідає результату Індексація: 0 - крос 1 - зразок 2 - результат ''' Path = ['','',''] # Шляхи до файлів Root = os.getcwd() # Поточний каталог FiltersPath = os.path.join(os.getcwd(),"filters.csv") # База фільтрів Types = {'c': 0, 's': 1, 'r': 2} K = 0. # Коефіцієнт калібровки kPICODict = {b'1064':5.03*10**-3, b'532':0.002,b"633" : 0.003} #Ai2 = 0. # Квадрат радіуса пучка по інтенсивності filtersDict = {} # Словник фільтрів filtList = ([1.,1.],[1.,1.]) # Поточні фільтри LENGTH = b"1064" # Довжина хвилі за замовчуванням # Стек історії для кроса. зразка і результата dataStack = ( [Array(sp.zeros((0,2)), Type = 0, scale=[0,0])], [Array(sp.zeros((0,2)), Type = 1, scale=[0,0])], [Array(sp.zeros((0,2)), Type = 2, scale=[0,0])] ) showTmp = False # Показувати проміжні побудови # DataUpdated signal -> slot # Сигнал про зміну в даних data_signal = QtCore.pyqtSignal(int, int, name = "dataChanged") def __init__(self, parent = None): super(QTR, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.fileDialog = QtGui.QFileDialog(self) self.qcut = DesignerMainWindow(parent = self) #self.qcut.show() # Відкат даних із QCut self.qcut.dataChanged.connect(self.getBackFromQcut) #self.qcut.show() self.intensDialog = IntensDialog() self.calibrDialog = CalibrDialog(self.Root) self.ui.tab_2.setEnabled(False) self.ui.tab_3.setEnabled(False) self.ui.tab_4.setEnabled(False) QtGui.QShortcut(QtGui.QKeySequence("Ctrl+Q"), self, self.close) ##### Signals -> Slots ######################################### self.uiConnect() # Пошук однотипних об’єктів графічної форми за кортежем імен def findChilds(self,obj,names, p = ''): '''Додатковий механізм пошуку об’єктів графічної форми p - атрибут який повертається для кожного елемента ''' if p == 'value': return tuple(self.findChild(obj,name).value() for name in names) elif p == 'checkState': return tuple(self.findChild(obj,name).checkState() for name in names) else: return tuple(self.findChild(obj,name) for name in names) def findUi(self, names, p = ''): if p == 'value': return [ getattr(self.ui, i).value() for i in names ] else: return [ getattr(self.ui, i) for i in names ] #################################################################### ######################## Обробка ################################# #################################################################### # Механічна обрізка def poly_cut(self, data, Start = None, End = None, N = 10, m = 4, p = 0.80, ASC=0): ''' Обрізка вздовж кривої апроксиміції поліномом. m - степінь полінома p - відсоток від максимального викиду N - кількість вузлів ASC - обробити Все, зробити Зріз, Зшити ''' X, Y = data[:,0], data[:,1] tmpData = [] if ASC in (1, 2): x, y = X.copy(), Y.copy() #Обрізка в заданих межах if not Start is None: if 0 < Start < X.max(): X, Y = X[X >= Start], Y[X >= Start] else: Start = X.min() if not End is None: if 0 < End <= X.max(): X, Y = X[X <= End], Y[X <= End] else: End = X.max() else: pass n = int(N) if self.showTmp: tmpData = (X, Y) EQ = sp.poly1d( sp.polyfit(X, Y, m) ) poly_Y = EQ( X ) xnew, ynew = [], [] Range = range(0,len(X),n) i = 0 for j in list(Range[1:])+[len(X)-1]: if j-i<=1: break x_temp = X[i:j] y_temp = Y[i:j] polyY_temp = poly_Y[i:j] t = True y_old = y_temp - polyY_temp std = sp.std(y_old) window = [] width = 0 for count in range(400): width = ( abs(y_old).max()*p ) window.append( abs(y_old) < width) y_new = y_old[window[-1]] t = ((sp.std(y_new)/std) >= p) y_old = y_new if not t: break for i in window: x_temp, y_temp = x_temp[i], y_temp[i] xnew = xnew + x_temp.tolist() ynew = ynew + (y_temp).tolist() i = j X, Y = sp.array(xnew), sp.array(ynew) if ASC == 2: less, more = x<X[0], x>X[-1] x1, x2 = x[less], x[more] y1, y2 = y[less], y[more] X, Y = sp.concatenate([x1, X, x2]), sp.concatenate([y1, Y, y2]) if self.showTmp: return Array(sp.array([X, Y]).T, Type = data.Type, scale = data.scale),\ tmpData, poly_Y else: return Array(sp.array([X, Y]).T, Type = data.Type, scale = data.scale) # Усереднення def averaging(self, data, Start = None, End = None, N = 1, m = 3): ''' Усереднення між заданими вузлами. m - порядок полінома N - кількість вузлів ''' x, y = data[:,0], data[:,1] #Обрізка в заданих межах if not Start is None: if 0 < Start < x.max(): x, y = x[x >= Start], y[x >= Start] if not End is None: if 0 < End <= x.max(): x, y = x[x <= End], y[x <= End] n = int(N) EQ = sp.poly1d( sp.polyfit(x, y, m) ) poly_Y = EQ( x ) Range = range(0,len(x),n) i = 0 xnew, ynew = [], [] for j in list(Range[1:])+[len(x)-1]: if j-i <=1: break x_temp = x[i:j].mean() xnew.append(x_temp) ynew.append( (y[i:j] - poly_Y[i:j]).mean() + EQ(x_temp)) i = j if self.showTmp: return Array(sp.array([xnew, ynew]).T, Type = data.Type, scale = data.scale), x, y, poly_Y else: return Array(sp.array([xnew, ynew]).T, Type = data.Type, scale = data.scale) # Інтерполяція b-сплайном def b_s(self, data, xi = [], Start = None, End = None, Step = 1, sm = 1100000., km = 5): ''' Інтерполяція B-сплайном sm - коефіцієнт згладжування km - степінь полінома ''' print("B-spline interpolation [s = %.3f, k = %.3f]" % (sm,km)) x, y = data[:,0], data[:,1] #Обрізка в заданих межах if not Start is None: if 0 < Start < x.max(): x, y = x[x >= Start], y[x >= Start] if not End is None: if 0 < End <= x.max(): x, y = x[x <= End], y[x <= End] if not any(xi): xi = sp.arange(Start, End,Step) try: y_interp = sp.interpolate.UnivariateSpline(x, y, s = sm, k = km)(xi) if self.showTmp: return Array(sp.array([xi, y_interp]).T,Type = data.Type, scale = data.scale), x, y else: return Array(sp.array([xi, y_interp]).T,Type = data.Type, scale = data.scale) except: pass self.mprint(error="ResEvalError", message="UnivariateSpline") #################################################################### ######################## Слоти ################################### #################################################################### def plotTmp(self, state): '''Проміжні побудови''' self.showTmp = state if not state: self.qcut.update_graph() def setLength(self, length): '''Вибір довжини хвилі зі списку''' self.LENGTH = length.encode('utf_8') if self.ui.typeExp.currentIndex() == 1: self.K = self.kPICODict[self.LENGTH] self.ui.calibr.setText(str(self.K)) else: pass def applyFilt(self): '''Застосування фільтрів із бази для відповідних XY''' key = self.sender().objectName()[0] index = self.Types[key] active = self.findUi([key + i + 'Filt' for i in ('X','Y')]) if not len(self.filtersDict)>0: self.filtersDict = self.getFilters(length = self.LENGTH) filtBaseNames = list(self.filtersDict.keys()) print(filtBaseNames) M = [1.,1.] for i in (0,1): Filt = active[i].text().upper().strip().replace(" ","").replace('+',',').split(',') check = [] if len(Filt)>=1: for j in Filt: #print(j) check.append(j.encode('utf-8') in filtBaseNames) else: Filt = ['1'] check = [1.] #print(check) check = sp.multiply.reduce(check) #print(check) if check: M[i] = self.resFilters(Filt) if M[0]!=1. or M[1]!=1.: for i in [0,1]: self.filtList[index][i] = M[i] data = self.getData(index) data[:,0] = data[:,0]/self.filtList[index][0] data[:,1] = data[:,1]/self.filtList[index][1] self.updateData(array = data) #self.mprint("Filters [X,Y]: %s" % str(self.filtList[index])) def AllSliceConcat(self, index): key = self.sender().objectName()[0] Type = self.Types[key] if index == 0: data = self.getData(Type) getattr(self.ui, key + 'Start').setValue(data[:,0].min()) getattr(self.ui, key + 'End').setValue(data[:,0].max()) # Повернути масштаб при поверненні в історії def setPrevScale(self, Type, action): Names = ( 'Y_XScale', 'XLogScale', 'YLogScale', 'LogScale' ) Types = ('c', 's', 'r') if action == 0 or action == -1: data = self.getData(Type) scale = data.Scale() ui_obj = self.findUi(( Types[Type] + i for i in Names)) for t in ui_obj[:-1]: t.toggled[bool].disconnect(self.setNewScale) if scale[1] == 2: ui_obj[0].setChecked(True) else: ui_obj[0].setChecked(False) ui_obj[1].setChecked(scale[0]) ui_obj[2].setChecked(scale[1]) ui_obj[0].setEnabled( not (ui_obj[1].isChecked() or ui_obj[2].isChecked())) ui_obj[3].setEnabled( not ui_obj[0].isChecked() ) for t in ui_obj[:-1]: t.toggled[bool].connect(self.setNewScale) else: pass # Змінити масштаб на новий def setNewScale(self, state): Names = ( 'Y_XScale', 'XLogScale', 'YLogScale', 'LogScale' ) Types = {'c' : 0, 's' : 1, 'r' : 2} senderName = self.sender().objectName() t, Type = senderName[0], Types[senderName[0]] data = self.getData(Type) Scale = data.Scale() ui_obj = self.findUi([t + i for i in Names]) if senderName[1:] == Names[0]: #ui_obj = getattr(self.ui, t + "LogScale") if state: Scale[1] = 2 data[:,1] = data[:,1] / data[:,0] else: Scale[1] = 0 data[:,1] = data[:,1] * data[:,0] ui_obj[3].setEnabled(not ui_obj[0].isChecked()) else: index = bool(senderName[1] != "X") #ui_obj = getattr(self.ui, t + Names[0]) if Scale[index] != state: if state == 1: data[:,index] = sp.log10(data[:,index]) else: data[:,index] = sp.power(10.,data[:,index]) Scale[index] = int(state) ui_obj[0].setEnabled(not (ui_obj[1].isChecked() or ui_obj[2].isChecked())) self.updateData(array = Array(data, Type = Type, scale = Scale)) def Save(self): '''Збереження активного масиву до текстового файлу''' Dict = {'cSave' : 0, 'sSave' : 1, 'rSave' : 2} senderName = self.sender().objectName() active = Dict[senderName] data = self.getData(active) filename = QtGui.QFileDialog.getSaveFileName(self,'Save File', self.Root) if filename: sp.savetxt(str(filename), data) def AutoB_splineS(self, state, isSignal = True, senderType = 0, param = 0.95): '''Штучний підбір коефіцієнтів для b-сплайн інтерполяції''' Dict = { 'cAutoB_splineS' : (0, 'cB_splineS', 'cB_splineStep', 'cB_splineK'), 'sAutoB_splineS' : (1, 'sB_splineS', 'sB_splineStep', 'sB_splineK'), 'rAutoB_splineS' : (2, 'rB_splineS', 'rB_splineStep', 'rB_splineK')} senderName = '' if isSignal: senderName = self.sender().objectName() else: Names = ['c', 's', 'r'] senderName = Names[senderType]+'AutoB_splineS' active = (Dict[senderName][0],) + self.findChilds(QtGui.QDoubleSpinBox,Dict[senderName][1:]) data = self.getData(active[0]) if state: active[1].setEnabled(False) y = data[:,1] x = data[:,0] EQ = sp.poly1d( sp.polyfit(x, y, 3) ) poly_Y = EQ( x ) Y = y - poly_Y Step = float(active[2].value()) K = float(active[3].value()) try: print(str((1+Step/K**3)*param)) active[1].setValue(sp.std(Y)**2*len(y)*(1+Step/K**2)*param) except: print("AutoB_splineS: SmoothParamError") else: active[1].setEnabled(True) def ResEval(self): """ Обчислюємо результат.""" ''' Param = ( (self.ui.cStart.value(), self.ui.cEnd.value(), self.ui.cAverageStep.value()), (self.ui.sStart.value(), self.ui.sEnd.value(), self.ui.sAverageStep.value())) ''' cData = self.getData(0) sData = self.getData(1) if cData.scale == [0,0] and sData.scale == [0,0]: if self.ui.rButton.isEnabled(): x = sData[:,0] window = (x>=cData[:,0].min())*(x<=cData[:,0].max()) x = x[window] y = sData[:,1] y = y[window] cY_temp = sp.interpolate.interp1d(cData[:,0], cData[:,1],self.ui.rEvalType.currentText().lower())(x) y = y/ cY_temp else: print('ResEval: interpTypeError') self.updateData(array = Array(sp.array([x,y]).T, Type = 2, scale = [0,0]),action = 0) else: print('ResEval: scaleError') def polyCut(self): '''Обрізка [за різними методами]''' '''Dict = {'cPolyOk' : (0,'cPolyN', 'cPolyP', 'cPolyM', 'cStart', 'cEnd'), 'sPolyOk' : (1,'sPolyN', 'sPolyP', 'sPolyM', 'sStart', 'sEnd')} ''' Types = {'c': 0, 's' : 1, 'r' : 2} Param = ('PolyN', 'PolyP', 'PolyM', 'Start', 'End') senderName = self.sender().objectName() Type = Types[senderName[0]] active = [Type] + self.findUi((senderName[0] + i for i in Param),p="value") XY = self.getData(active[0]) ASC = getattr(self.ui, senderName[0] + "AllSliceConcat").currentIndex() data = self.poly_cut(XY, N = active[1], p = active[2], m = active[3], Start = active[4], End = active[5], ASC = ASC) if self.showTmp: data, tmp, poly_Y = data self.updateData(array = data.copy()) if self.showTmp: self.ui.mpl.canvas.ax.plot(tmp[0], tmp[1], '.m', alpha=0.2, zorder=1) self.ui.mpl.canvas.ax.plot( tmp[0], poly_Y, 'r') self.ui.mpl.canvas.draw() def Average(self): '''Усереднення за різними методами''' Dict = {'cAverageOk' : (0,'cStart', 'cEnd', 'cAverageStep'), 'sAverageOk' : (1,'sStart', 'sEnd', 'sAverageStep')} senderName = self.sender().objectName() tmp = Dict[senderName] active = (tmp[0],) + self.findChilds(QtGui.QDoubleSpinBox,tmp[1:],p="value") XY = self.getData(active[0]) data = self.averaging(XY, Start = active[1], End = active[2], N = active[3] ) if self.showTmp: data, x, y, poly_Y = data self.updateData(array = data) if self.showTmp: self.ui.mpl.canvas.ax.plot(x, y, '.m', alpha=0.2, zorder=1) self.ui.mpl.canvas.ax.plot( x, poly_Y, 'r') self.ui.mpl.canvas.draw() def medFilt(self): '''Фільтрація медіаною''' Dict = {'cMedFilt' : (0,'cMedFiltS'), 'sMedFilt' : (1,'sMedFiltS'), 'rMedFilt' : (2,'rMedFiltS')} senderName = self.sender().objectName() active = (Dict[senderName][0], self.findChild(QtGui.QSpinBox, Dict[senderName][1]).value()) XY = self.getData(active[0]) X, Y = XY[:,0], XY[:,1] EQ = sp.poly1d( sp.polyfit(X, Y, 4) ) # можна додати прив’язку до степ. поліному poly_Y = EQ( X ) y_temp = Y - poly_Y y = medfilt(y_temp, kernel_size = active[1]) Y_new = y + poly_Y self.updateData(array = Array(sp.array([X, Y_new]).T, Type = XY.Type, scale = XY.scale)) if self.showTmp: self.ui.mpl.canvas.ax.plot(X, Y, '.m', alpha=0.2, zorder=1) self.ui.mpl.canvas.ax.plot( X, poly_Y, 'r') self.ui.mpl.canvas.draw() def B_spline(self): '''інтерполяція b-сплайном''' Dict = { 'cB_splineOk' : (0,'cStart', 'cEnd', 'cB_splineStep', 'cB_splineS', 'cB_splineK'), 'sB_splineOk' : (1,'sStart', 'sEnd', 'sB_splineStep', 'sB_splineS', 'sB_splineK'), 'rB_splineOk' : (2,'rStart', 'rEnd', 'rB_splineStep', 'rB_splineS', 'rB_splineK')} senderName = self.sender().objectName() active = (Dict[senderName][0],) + self.findChilds(QtGui.QDoubleSpinBox, Dict[senderName][1:],p = 'value') XY = self.getData(active[0]) data = self.b_s(XY, Start = active[1], End = active[2], Step = active[3], sm = active[4], km = int(active[5])) if self.showTmp: data, x, y = data self.updateData(array = data) if self.showTmp: self.ui.mpl.canvas.ax.plot(x, y, '.m', alpha=0.5, zorder=1) self.ui.mpl.canvas.draw() def Undo(self): '''Відкат до попередніх даних''' Dict = {'cUndo' : 0, 'sUndo' : 1, 'rUndo' : 2} senderName = self.sender().objectName() Type = Dict[senderName] if len(self.dataStack[Type])>=2: self.updateData(Type = Type, action = -1) else: self.sender().setEnabled(False) def Reset(self): '''Скидання історії''' Dict = {'cReset' : 0, 'sReset' : 1, 'rReset' : 2} senderName = self.sender().objectName() Type = Dict[senderName] if len(self.dataStack[Type])>=2: self.updateData(Type = Type, action = 0) else: self.sender().setEnabled(False) def plotCurrent(self, index): '''Побудова поточної вкладки''' if index > 0: Type = index-1 if sp.any(self.getData(Type)): active = self.getData(Type); #if not self.qcut.isVisible(): # self.qcut.setVisible(True) #else: pass self.Plot(active) else: pass else: pass def getBackFromQcut(self): ''' Отримання даних, що змінені вручну в QCut''' try: print( "QCut -> "+str(sp.shape(self.qcut.tdata)), self.qcut.tdata.Type, self.qcut.tdata.scale) data, Type, Scale = self.qcut.getData() self.updateData( array = Array(data, Type = Type, scale=Scale) ) except: pass def pathTextChanged(self, text): """Якщо поле з шляхом до файлу для завантаження було змінене""" Dict = {'cPath' : (0, 'cLoad'), 'sPath' : (1, 'sLoad')} sender = self.sender() tmp = Dict[sender.objectName()] active = [tmp[0]] + [self.findChild(QtGui.QPushButton,tmp[1])] if os.path.exists(str(sender.text())): self.Path[active[0]] = str(sender.text()) if not active[1].isEnabled(): active[1].setEnabled(True) else: active[1].setEnabled(False) def getFilePath(self): '''Вибір файлу для завантаження''' Dict = {'cFile' : (0, 'cPath', 'cLoad'), 'sFile' : (1, 'sPath', 'sLoad')} senderName = self.sender().objectName() tmp = Dict[senderName] active = [tmp[0]] + [self.findChild(QtGui.QLineEdit,tmp[1])] + [self.findChild(QtGui.QPushButton,tmp[2])] path = str(self.fileDialog.getOpenFileName(self,'Open File', self.Root)) if path: self.Root = os.path.dirname(path) self.Path[active[0]] = path active[1].setText(self.Path[active[0]]) active[2].setEnabled(True) def loadData(self): '''Завантаження даних з файлів''' Tabs = ( ('tab_2', 'tab_3','tab_4'), ('tab_3', 'tab_2','tab_4')) uiObj = ('XColumn', 'YColumn', 'MColumn', 'MCheck') senderName = self.sender().objectName() key = senderName[0] active = [self.Types[key]] + self.findUi( [key + i for i in uiObj]) data = [] XY = sp.zeros((0,2)) path = self.Path[active[0]] if os.path.exists(path): try: data = sp.loadtxt(path) ''' activeFilt = self.findChilds(QtGui.QLineEdit, FiltersKeys[active[0]]) filtNames = '' if activeFilt[0].isEnabled() and activeFilt[1].isEnabled(): self.filtersDict = self.getFilters(length = self.LENGTH) for i in (0,1): filtNames = activeFilt[i].text().strip().replace(" ","").upper() temp = 1. if filtNames: temp = self.resFilters(filtNames) self.filtList[active[0]][i] = temp else: self.filtList[active[0]][:] = [1., 1.] print("Filters [X,Y]:",self.filtList[active[0]]) ''' xc = active[1].value() yc = active[2].value() mc = active[3].value() if active[4].checkState(): XY = sp.array( [data[:,xc], data[:,yc] ]).T / sp.array([data[:,mc], data[:,mc]]).T else: XY = sp.array( [data[:,xc], data[:,yc] ]).T XY = XY[XY[:,0] > 0] XY = XY[XY[:,1] > 0] if getattr(self.ui,senderName[0]+'CutForward').isChecked(): p = sp.where( XY[:,0] == XY[:,0].max())[0][0] print(p) XY = XY[:p,:] XY = XY[sp.argsort(XY[:,0])] ''' XY[:,0] = XY[:,0]/self.filtList[active[0]][0] XY[:,1] = XY[:,1]/self.filtList[active[0]][1] ''' self.updateData(array = Array(XY,Type = active[0]), action = 0) tabs = self.findUi(Tabs[active[0]]) tabs[0].setEnabled(True) if tabs[1].isEnabled(): tabs[2].setEnabled(True) except (ValueError, IOError, IndexError): self.mprint("loadData: readError") else: self.mprint('loadData: pathError') def dataListener(self,Type, action): """Обробка зміни даних""" Buttons = ( ('cUndo', 'cReset'), ('sUndo', 'sReset'), ('rUndo', 'rReset')) Types = ['c','s','r'] active = self.getData(Type) self.mprint("dataChanged: scaleX : %d, scaleY : %d, type : %d, len : %d, action : %d" %\ (active.scaleX, active.scaleY ,active.Type, sp.shape(active)[0],action)) #for i in self.dataStack[Type]: # print(i.scale) if sp.any(active): #intervalCheck = ['cAutoInterval', 'sAutoInterval', 'rAutoInterval'] b_splineSCheck = ['cAutoB_splineS', 'sAutoB_splineS', 'rAutoB_splineS'] #intervalObj = self.findChild(QtGui.QCheckBox,intervalCheck[Type]) b_splineSObj = self.findChild(QtGui.QCheckBox,b_splineSCheck[Type]) #self.AutoInterval(intervalObj.checkState(), isSignal = False, senderType = Type) if getattr(self.ui,Types[Type] + 'AllSliceConcat').currentIndex() == 0: getattr(self.ui,Types[Type] + 'Start').setValue(active[:,0].min()) getattr(self.ui,Types[Type] + 'End').setValue(active[:,0].max()) self.AutoB_splineS(b_splineSObj.checkState(), isSignal = False, senderType = Type ) ##### Undo/Reset hist = self.dataStack[Type] state = False if len(hist)>=2: state = True buttons = self.findChilds(QtGui.QPushButton,Buttons[Type]) buttons[0].setEnabled(state) buttons[1].setEnabled(state) def closeEvent(self, event): #self.qcut.close() if hasattr(self, 'intensDialog' ): self.intensDialog.close() #======================= intens ============================= def calibrChanged(self): text = self.sender().text() K = 0. try: K = float(text) except: K = self.K self.sender().setText(str(K)) self.K = K def typeExp(self, index): if index == 0: self.ui.recalcCalibr.setEnabled(True) if index == 1: self.K = self.kPICODict[self.LENGTH] self.ui.calibr.setText(str(self.K)) ''' k = 0 try: k = float(self.ui.calibr.text()) except: pass if k: self.K = k ''' self.ui.recalcCalibr.setEnabled(False) def recalcCalibr(self): self.calibrDialog.show() def recalcForIntens(self): self.intensDialog.show() print(self.intensDialog.Ai2) #self.ui_intensDialog = Ui_Dialog() #self.ui_intensDialog.setupUi(self) #self.ui_intensDialog. def getIntens(self): Ai2 = self.intensDialog.Ai2 K = self.K data = self.getData(2) data[:,0] *= K/sp.pi/Ai2 self.updateData(Array(data, scale = data.scale, Type = 2)) self.intensDialog.hide() def getCalibr(self): self.K = self.calibrDialog.K self.ui.calibr.setText(str(self.K)) self.calibrDialog.hide() self.calibrDialog.qcut.hide() #################################################################### ######################## Допоміжні методи ######################## #################################################################### def mprint(self, m): '''Вивід повідомлень в поле статусу''' self.ui.statusbar.showMessage(m) print(m) def Plot(self, array): self.qcut.Plot(array) def updateData(self, array = Array(sp.zeros((0,2)),scale=[0,0], Type = 0), action = 1, Type = None): """ Запис в тимчасовий файл даних з масиву action = {-1, 0, 1, 2} -1 : undo 0 : reset 1 : add """ if Type is None: if sp.any(array): Type = array.Type #print(sp.shape(array),array.Type) emit = False #print(len(self.dataStack[Type]),action) # Запис в історію if action == 1: if sp.any(array) and sp.shape(array)[1] == 2 and sp.shape(array)[0] > 1: self.dataStack[Type].append(array) emit = True else: print('updateData: arrayError',sp.any(array) , sp.shape(array)[1] == 2 , sp.shape(array)[0] > 1) # Видалення останнього запису elif action == -1 and len(self.dataStack[Type])>=2: self.dataStack[Type].pop() emit = True #self.setActiveLogScale( Type) # Скидання історії, або запис першого елемента історії elif action == 0: print(0) if sp.any(array) and sp.shape(array)[1] == 2 and sp.shape(array)[0] > 1 and len(self.dataStack[Type])>=1: self.dataStack[Type][0:] = [] self.dataStack[Type].append(array) emit = True if not sp.any(array) and len(self.dataStack[Type])>=2: self.dataStack[Type][1:] = [] emit = True #self.setActiveLogScale( Type) else: print("updateData: Error0",len(self.dataStack[Type])) print(sp.shape(self.getData(Type))) try: for i in self.dataStack[Type]: print(i.scaleX, i.scaleY, i.shape) except: pass # Емітувати повідомлення про зміу даних if emit: self.data_signal.emit(Type, action) self.Plot(self.getData(Type) ) def getData(self,Type): return self.dataStack[Type][-1].copy() def getFilters(self, length="532"): """Читання таблиці фільтрів та вибір значень для даної довжини хвилі""" filt = sp.loadtxt(self.FiltersPath, dtype="S") col = sp.where(filt[0,:]==length)[0][0] return dict( zip(filt[1:,0], sp.array(filt[1:,col],dtype="f") ) ) def resFilters(self,filters): """Перерахунок для різних комбінацій фільтрів""" return sp.multiply.reduce( [ self.filtersDict[i.encode('utf-8')] for i in filters] ) def uiConnect(self): '''Пов’язвння сигналів з слотами''' self.ui.cFile.clicked.connect(self.getFilePath) self.ui.sFile.clicked.connect(self.getFilePath) self.ui.cLoad.clicked.connect(self.loadData) self.ui.sLoad.clicked.connect(self.loadData) self.ui.cPath.textChanged.connect(self.pathTextChanged) self.ui.sPath.textChanged.connect(self.pathTextChanged) self.ui.tabWidget.currentChanged[int].connect(self.plotCurrent) self.ui.cMCheck.toggled[bool].connect(self.ui.cMColumn.setEnabled) self.ui.sMCheck.toggled[bool].connect(self.ui.sMColumn.setEnabled) self.ui.cUndo.clicked.connect(self.Undo) self.ui.sUndo.clicked.connect(self.Undo) self.ui.rUndo.clicked.connect(self.Undo) self.ui.cReset.clicked.connect(self.Reset) self.ui.sReset.clicked.connect(self.Reset) self.ui.rReset.clicked.connect(self.Reset) self.ui.cPolyOk.clicked.connect(self.polyCut) self.ui.sPolyOk.clicked.connect(self.polyCut) self.ui.cAverageOk.clicked.connect(self.Average) self.ui.sAverageOk.clicked.connect(self.Average) self.ui.cMedFilt.clicked.connect(self.medFilt) self.ui.sMedFilt.clicked.connect(self.medFilt) self.ui.rMedFilt.clicked.connect(self.medFilt) self.ui.cB_splineOk.clicked.connect(self.B_spline) self.ui.sB_splineOk.clicked.connect(self.B_spline) self.ui.rB_splineOk.clicked.connect(self.B_spline) self.ui.rButton.clicked.connect(self.ResEval) #self.ui.cAutoInterval.toggled[bool].connect(self.AutoInterval) #self.ui.sAutoInterval.toggled[bool].connect(self.AutoInterval) #self.ui.rAutoInterval.toggled[bool].connect(self.AutoInterval) self.ui.cAutoB_splineS.toggled[bool].connect(self.AutoB_splineS) self.ui.sAutoB_splineS.toggled[bool].connect(self.AutoB_splineS) self.ui.rAutoB_splineS.toggled[bool].connect(self.AutoB_splineS) self.ui.cSave.clicked.connect(self.Save) self.ui.sSave.clicked.connect(self.Save) self.ui.rSave.clicked.connect(self.Save) self.ui.tmpShow.toggled[bool].connect(self.plotTmp) ''' self.ui.cFilt.toggled[bool].connect(self.ui.cXFilt.setEnabled) self.ui.cFilt.toggled[bool].connect(self.ui.cYFilt.setEnabled) self.ui.sFilt.toggled[bool].connect(self.ui.sXFilt.setEnabled) self.ui.sFilt.toggled[bool].connect(self.ui.sYFilt.setEnabled) ''' self.ui.cFiltOk.clicked.connect(self.applyFilt) self.ui.sFiltOk.clicked.connect(self.applyFilt) #self.ui.rEvalType.activated[str].connect(self.interpTypeChanged) # Масштабування self.ui.cXLogScale.toggled[bool].connect(self.setNewScale) self.ui.cYLogScale.toggled[bool].connect(self.setNewScale) self.ui.sXLogScale.toggled[bool].connect(self.setNewScale) self.ui.sYLogScale.toggled[bool].connect(self.setNewScale) self.ui.rXLogScale.toggled[bool].connect(self.setNewScale) self.ui.rYLogScale.toggled[bool].connect(self.setNewScale) self.ui.cY_XScale.toggled[bool].connect(self.setNewScale) self.ui.sY_XScale.toggled[bool].connect(self.setNewScale) self.ui.rY_XScale.toggled[bool].connect(self.setNewScale) self.ui.cAllSliceConcat.currentIndexChanged[int].connect(self.AllSliceConcat) self.ui.sAllSliceConcat.currentIndexChanged[int].connect(self.AllSliceConcat) self.ui.rAllSliceConcat.currentIndexChanged[int].connect(self.AllSliceConcat) #self.close.connect(self.closeEvent) self.ui.LENGTH.currentIndexChanged[str].connect(self.setLength) #________________________________________________ self.data_signal[int,int].connect(self.dataListener) self.data_signal[int,int].connect(self.setPrevScale) #+++++++++++++++++++ Intensity ++++++++++++++++++++++++++++++++++++++++++++++++ self.ui.typeExp.currentIndexChanged[int].connect(self.typeExp) self.ui.calibr.editingFinished.connect(self.calibrChanged) #################### intensDialog ################################################ self.ui.recalcForIntens.clicked.connect(self.recalcForIntens) self.intensDialog.ui.buttonBox.accepted.connect(self.getIntens) #################### calibrDialog ################################################ self.calibrDialog.ui.ok.clicked.connect(self.getCalibr) self.ui.recalcCalibr.clicked.connect(self.recalcCalibr) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! def setTool(self,objType, objName): return self.findChild(objType,objName)
class MyDialog(QtGui.QMainWindow): def __init__(self, parent=None): # Initialize window QtGui.QWidget.__init__(self,parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Initialize search list (on left) self.lstSearch = self.ui.lstSearch self.modelSearch = QtGui.QStandardItemModel(self.lstSearch) # Initialize similar list (on right) self.lstSimilar = self.ui.lstSimilar self.modelSimilar = QtGui.QStandardItemModel(self.lstSimilar) # Define functions for buttons self.ui.btnDone.clicked.connect(self.close) self.ui.btnSearch.clicked.connect(self.search) self.ui.btnAdd.clicked.connect(self.add) self.ui.btnRem.clicked.connect(self.rem) # KeyEvent filter to filter out when you press the return key self.ui.searchtext.installEventFilter(self) # Go into the database and get list def getdat(self,inputdata): host = 'localhost' dbname = 'myndir' #username = input('User name for {}.{}: '.format(host,dbname)) username = '******' #pw = getpass.getpass() pw = 'Hjol5106' conn_string = "host='{}' dbname='{}' user='******' password='******'".format(host, dbname, username, pw) conn = psycopg2.connect(conn_string) cursor = conn.cursor() #print("Connected!\n") s = ("""select title, year from movies where lower(title) like '%{}%' or year like'%{}%' order by title;""".format(inputdata.lower(),inputdata)) cursor.execute(s) #pp.pprint(cursor.fetchall()) return cursor.fetchall() def search(self): # Clear listbox self.modelSearch.clear() # Get text from textbox and clear it txt = self.ui.searchtext.toPlainText() self.ui.searchtext.clear() # Get data from sql database movielistoftuple = self.getdat(txt) for i in movielistoftuple: # Get each line of text txt = i[0] + ' ({})'.format(i[1]) # Create item from text and add to list item = QtGui.QStandardItem(txt) item.setEditable(False) #Add to the list self.modelSearch.appendRow(item) # Make sure list appears self.lstSearch.setModel(self.modelSearch) def add(self): # Get index for selected item index = self.lstSearch.selectedIndexes()[0] # Get item associated with selected index item = self.modelSearch.itemFromIndex(index) newitem = QtGui.QStandardItem(item.text()) newitem.setEditable(False) # Remove item from search list self.modelSearch.removeRow(index.row()) self.lstSearch.setModel(self.modelSearch) # Move to similar list self.modelSimilar.appendRow(newitem) self.lstSimilar.setModel(self.modelSimilar) def rem(self): # Get index for selected item index = self.lstSimilar.selectedIndexes()[0] # Get item associated with selected index item = self.modelSimilar.itemFromIndex(index) newitem = QtGui.QStandardItem(item.text()) newitem.setEditable(False) # Remove item from similar list self.modelSimilar.removeRow(index.row()) self.lstSimilar.setModel(self.modelSimilar) # Move to search list self.modelSearch.appendRow(newitem) self.lstSearch.setModel(self.modelSearch) def eventFilter(self, obj, event): # Call the search function if you press Return if event.type() == QtCore.QEvent.KeyPress and event.key() == QtCore.Qt.Key_Return: self.search() return True # Default case, writes text to the textbox QtGui.QWidget.eventFilter(self, obj, event) return False
class Program(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) print "ui coplite" try: self.MicListen_thread = MicListen() self.connect(self.MicListen_thread, QtCore.SIGNAL('mouthValue(float)'), self.mouthValue) self.MicListen_thread.start() self.ui.micStat.setText("OK!") except: self.ui.micStat.setText("Not found microphone!") print "" self.gui_Connect() print "gui connect complite" self.lastMaxProgressBarValue = 100 self.lastTextSend = 0 self.colorsButtons =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.colorsButtonsList = [ """ background-color: rgb(255,0,0); border:1px solid rgb(0,0,0); """, """ background-color: rgb(255,255,0); border:1px solid rgb(0,0,0); """, """ background-color: rgb(0,255,255); border:1px solid rgb(0, 0, 0); """, """ background-color: rgb(255,0,255); border:1px solid rgb(0, 0, 0); """, """ background-color: rgb(0,0,0); border:1px solid rgb(0, 0, 0); """ ] self.shortColorsButtonsList = [ "255,0,0", "255,255,0", "0,255,255", "255,0,255", "0,0,0", "255,192,203",#pink "0,0,139", #darkblue "255,255,255", #white "0,110,0", #darkgreen "255, 215, 0" #gold ] self.loadColorGui() # self.connect(self.get_thread, QtCore.SIGNAL("finished()"), self.done) print "load color gui complite" self.updatePortList() #self.ui.portBox.activated['QString'].connect(self.updatePort) self.connect(self.ui.portBox, QtCore.SIGNAL('activated(QString)'), self.updatePort) #self.ui.portBox.clicked.connect(self.updatePortList) def loadColorGui(self): for i in xrange(10): #print self.shortColorsButtonsList[i] self.colorsButtons[i] = QtGui.QPushButton("") self.colorsButtons[i].clicked.connect(self.sendColor) color = """ background-color: rgb("""+self.shortColorsButtonsList[i]+"""); border:1px solid rgb(0,0,0); """ self.colorsButtons[i].setStyleSheet(color) self.colorsButtons[i].setMaximumWidth(23) self.colorsButtons[i].setMaximumHeight(23) self.colorsButtons[i].setMinimumWidth(23) self.colorsButtons[i].setMinimumHeight(23) if i>=5: self.ui.colorLayout.addWidget(self.colorsButtons[i], 1, i-5) else: self.ui.colorLayout.addWidget(self.colorsButtons[i], 0, i) def getPortList(self): if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): ports = glob.glob('/dev/tty[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/tty.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result def updatePortList(self): port_name = self.getPortList() self.ui.portBox.clear() print port_name for i in port_name: print i self.ui.portBox.addItem(i) def updatePort(self, name): global port, PORT_ACTIVE try: port.close() except: try: port = serial.Serial(str(name), baudrate=BAUD_RATE, dsrdtr=1, timeout=3.0) PORT_ACTIVE = True self.ui.arduinoStat.setText("Connection: " + name) except: self.ui.arduinoStat.setText("Connection lost") PORT_ACTIVE = False def sendColor(self): colorIndex = self.colorsButtons.index(self.sender()) colors = self.shortColorsButtonsList[colorIndex].split(",") sendData = "DR" + colors[0] + "G" + colors[1] + "B" + colors[2] + "\n" self.emit(QtCore.SIGNAL('sendData(QString)'), sendData) def gui_Connect(self): self.connect(self.ui.sevoPosSlider, QtCore.SIGNAL('valueChanged(int)'), self.sevoPosSliderEvent) self.connect(self.ui.sevoPosSlider, QtCore.SIGNAL('valueChanged(int)'), self.ui.posValue, QtCore.SLOT('setNum(int)')) self.connect(self.ui.delaySlider, QtCore.SIGNAL('valueChanged(int)'), self.ui.delayValue, QtCore.SLOT('setNum(int)')) self.connect(self.ui.openSlider, QtCore.SIGNAL('valueChanged(int)'), self.ui.openValue, QtCore.SLOT('setNum(int)')) self.connect(self.ui.open12Slider, QtCore.SIGNAL('valueChanged(int)'), self.ui.open12Value, QtCore.SLOT('setNum(int)')) self.connect(self.ui.closeSlider, QtCore.SIGNAL('valueChanged(int)'), self.ui.closeValue, QtCore.SLOT('setNum(int)')) ###For headtrecker### self.connect(self.ui.minXSlider, QtCore.SIGNAL('valueChanged(int)'), self.headTreckXSettingsEvent) self.connect(self.ui.maxXSlider, QtCore.SIGNAL('valueChanged(int)'), self.headTreckXSettingsEvent) self.connect(self.ui.minYSlider, QtCore.SIGNAL('valueChanged(int)'), self.headTreckYSettingsEvent) self.connect(self.ui.maxYSlider, QtCore.SIGNAL('valueChanged(int)'), self.headTreckYSettingsEvent) self.connect(self.ui.xHeadSlider, QtCore.SIGNAL('valueChanged(int)'), self.headRotationXEvent) self.connect(self.ui.xHeadSlider, QtCore.SIGNAL('valueChanged(int)'), self.ui.xHeadValue, QtCore.SLOT('setNum(int)')) self.connect(self.ui.yHeadSlider, QtCore.SIGNAL('valueChanged(int)'), self.headRotationYEvent) self.connect(self.ui.yHeadSlider, QtCore.SIGNAL('valueChanged(int)'), self.ui.yHeadValue, QtCore.SLOT('setNum(int)')) self.connect(self.ui.delaySliderHead, QtCore.SIGNAL('valueChanged(int)'), self.delayHeadTrekerEvent ) self.connect(self.ui.delaySliderHead, QtCore.SIGNAL('valueChanged(int)'), self.ui.delayValueHead, QtCore.SLOT('setNum(int)')) def headRotationXEvent(self): value = self.ui.xHeadSlider.value() sendData = "S|D12" + ">" + str(value) + "\n" self.emit(QtCore.SIGNAL('sendData(QString)'), sendData) def headRotationYEvent(self): value = self.ui.yHeadSlider.value() sendData = "S|D11" + ">" + str(value) + "\n" self.emit(QtCore.SIGNAL('sendData(QString)'), sendData) def delayHeadTrekerEvent(self): timeDelay = self.ui.delaySliderHead.value() sendData = "T" + "H" + str(timeDelay) + "\n" self.emit(QtCore.SIGNAL('sendData(QString)'), sendData) def headTreckXSettingsEvent(self): minX = self.ui.minXSlider.value() maxX = self.ui.maxXSlider.value() self.ui.minXValue.setText(str(minX)) self.ui.maxXValue.setText(str(maxX)) sendData = "QX"+"L" + str(minX) + "B" + str(maxX) + "R1" + "\n" self.emit(QtCore.SIGNAL('sendData(QString)'), sendData) def headTreckYSettingsEvent(self): minY = self.ui.minYSlider.value() maxY = self.ui.maxYSlider.value() self.ui.minYValue.setText(str(minY)) self.ui.maxYValue.setText(str(maxY)) sendData = "QY"+"L" + str(minY) + "B" + str(maxY) + "R1" + "\n" self.emit(QtCore.SIGNAL('sendData(QString)'), sendData) def mouthValue(self, value): gain = self.ui.gainBox.value() checkMouth = self.ui.mouthCheck.isChecked() bigValue = value*100*gain openValue = int(self.ui.openValue.text()) open12Value = int(self.ui.open12Value.text()) closeValue = int(self.ui.closeValue.text()) openMouth12Value = self.ui.sredValue.text() openMouthValue = self.ui.maxValue.text() closeMouthValue = self.ui.minValue.text() #self.lastTextSend = closeMouthValue if checkMouth: if bigValue > self.lastMaxProgressBarValue: self.ui.soundProgress.setMaximum(bigValue) self.lastMaxProgressBarValue = bigValue print self.lastMaxProgressBarValue if bigValue > openValue and self.lastTextSend!=openMouthValue: sendData = "M>" + openMouthValue + "\n" self.emit(QtCore.SIGNAL('sendData(QString)'), sendData) self.lastTextSend = openMouthValue elif bigValue < openValue and bigValue > open12Value and self.lastTextSend != openMouth12Value: sendData = "M>" + openMouth12Value + "\n" self.emit(QtCore.SIGNAL('sendData(QString)'), sendData) self.lastTextSend = openMouth12Value elif (int(bigValue) <= closeValue or int(bigValue) < open12Value)and self.lastTextSend!=closeMouthValue: sendData = "M>" + closeMouthValue + "\n" self.emit(QtCore.SIGNAL('sendData(QString)'), sendData) self.lastTextSend = closeMouthValue self.ui.soundProgress.setValue(bigValue) def sevoPosSliderEvent(self, value): #text = self.ui.openValue.text() #text2 = self.ui.open12Value.text() #self.emit(QtCore.SIGNAL('setPort(QString)'), text2) #self.ui.openValue.setText(str(value)) data = QtCore.QString("M>"+str(value)+"\n") self.emit(QtCore.SIGNAL('sendData(QString)'), data) pass
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) print "ui coplite" try: self.MicListen_thread = MicListen() self.connect(self.MicListen_thread, QtCore.SIGNAL('mouthValue(float)'), self.mouthValue) self.MicListen_thread.start() self.ui.micStat.setText("OK!") except: self.ui.micStat.setText("Not found microphone!") print "" self.gui_Connect() print "gui connect complite" self.lastMaxProgressBarValue = 100 self.lastTextSend = 0 self.colorsButtons =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.colorsButtonsList = [ """ background-color: rgb(255,0,0); border:1px solid rgb(0,0,0); """, """ background-color: rgb(255,255,0); border:1px solid rgb(0,0,0); """, """ background-color: rgb(0,255,255); border:1px solid rgb(0, 0, 0); """, """ background-color: rgb(255,0,255); border:1px solid rgb(0, 0, 0); """, """ background-color: rgb(0,0,0); border:1px solid rgb(0, 0, 0); """ ] self.shortColorsButtonsList = [ "255,0,0", "255,255,0", "0,255,255", "255,0,255", "0,0,0", "255,192,203",#pink "0,0,139", #darkblue "255,255,255", #white "0,110,0", #darkgreen "255, 215, 0" #gold ] self.loadColorGui() # self.connect(self.get_thread, QtCore.SIGNAL("finished()"), self.done) print "load color gui complite" self.updatePortList() #self.ui.portBox.activated['QString'].connect(self.updatePort) self.connect(self.ui.portBox, QtCore.SIGNAL('activated(QString)'), self.updatePort)
def __init__(self): super(App, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.df = pd.read_csv("worldometer_data.csv")
class Window(QtWidgets.QMainWindow): def __init__(self): super(Window, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.startButton.clicked.connect(self.btn_start_clicked) self.ui.barGraph.clicked.connect(self.btn_bar_graph_clicked) self.ui.correlation.clicked.connect(self.btn_correlation_clicked) self.ui.scatter.clicked.connect(self.btn_scatter_clicked) self.ui.barGraph_2.clicked.connect(self.btn_bar_graph_2_clicked) self.ui.correlation_2.clicked.connect(self.btn_correlation_2_clicked) self.ui.scatter_2.clicked.connect(self.btn_scatter_2_clicked) self.ui.radioButtonTask.toggled.connect(self.change_radio_btn) self.ui.radioButtonTask.toggled.connect(self.change_radio_btn) self.ui.pushButton_2.clicked.connect(self.plots) self.ui.pushButton_3.clicked.connect(self.avr_plots) self.ui.pushButton.clicked.connect(self.coefficient_plots) def btn_start_clicked(self): queue_size = int(self.ui.queueSize.text()) devices = int(self.ui.deviceCount.text()) process_time = float(self.ui.middleProcTime.text()) arrival_time = float(self.ui.middleArrivalTime.text()) if self.ui.radioButtonTask.isChecked(): finish_condition = int(self.ui.taskCounter.text()) sys_state = 2 else: finish_condition = float(self.ui.timeCounter.text().replace( ',', '.')) sys_state = 1 if queue_size > 0 and devices > 0 and process_time > 0 and arrival_time > 0 and finish_condition > 0: ans, self.que, self.dev = main(finish_condition, sys_state, devices, queue_size, process_time, arrival_time) for i in range(len(self.que.exp_dist_arrive) - 1, 1, -1): self.que.exp_dist_arrive[i] -= self.que.exp_dist_arrive[i - 1] self.ui.barGraph.setEnabled(True) self.ui.correlation.setEnabled(True) self.ui.scatter.setEnabled(True) self.ui.barGraph_2.setEnabled(True) self.ui.correlation_2.setEnabled(True) self.ui.scatter_2.setEnabled(True) self.ui.pushButton.setEnabled(True) self.ui.pushButton_2.setEnabled(True) self.ui.pushButton_3.setEnabled(True) self.ui.allTasks.setText('Всего: \n' + str(self.que.all_tasks)) self.ui.garbage.setText('Отказов: \n' + str(self.que.fail)) self.ui.readyTasks.setText('Обработано: \n' + str(self.que.ready)) self.create_table_dev(ans['devices']) self.create_table_info([ ans['p'], ans['Ns'], ans['Nq'], ans['Tq'], ans['Ts'], ans['Ca'], ans['Cr'] ]) m, d = estimates(self.que.exp_dist_arrive) self.ui.labelDisp.setText('= ' + str(d)) self.ui.labelExpectValue.setText('= ' + str(m)) self.ui.labelContInt.setText( confidence_interval(m, d, arrival_time, len(self.que.exp_dist_arrive))) m, d = estimates(self.que.exp_dist_prc) self.ui.labelDisp_2.setText('= ' + str(d)) self.ui.labelExpectValue_2.setText('= ' + str(m)) self.ui.labelContInt_2.setText( confidence_interval(m, d, process_time, len(self.que.exp_dist_prc))) def create_table_dev(self, devices): self.ui.tableWidget.clear() self.ui.tableWidget.setRowCount(len(devices)) self.ui.tableWidget.setColumnCount(1) for i in range(len(devices)): progress = QtWidgets.QProgressBar() progress.setMinimum(0) progress.setMaximum(100) progress.setValue(min(devices[i], 100)) progress.setFormat('{0:.2f}%'.format(devices[i])) progress.setAlignment(Qt.AlignCenter) progress.setStyleSheet("""QProgressBar::chunk { border: 2px solid rgb(36,53,129); background-color: lightblue; }""") self.ui.tableWidget.setCellWidget(i, 0, progress) self.ui.tableWidget.setHorizontalHeaderLabels(['Устройства']) def create_table_info(self, ans): self.ui.tableWidget_2.clear() self.ui.tableWidget_2.setRowCount(7) self.ui.tableWidget_2.setColumnCount(1) for i in range(7): self.ui.tableWidget_2.setItem(i, 0, QTableWidgetItem(str(ans[i]))) self.ui.tableWidget_2.setHorizontalHeaderLabels(['Отклики']) self.ui.tableWidget_2.setVerticalHeaderLabels( ('p', 'Ns', 'Nq', 'Tq', 'Ts', 'Ca', 'Cr')) def btn_bar_graph_clicked(self): bar_graph(self.que.exp_dist_arrive, float(self.ui.middleArrivalTime.text())) def btn_correlation_clicked(self): m, d = estimates(self.que.exp_dist_arrive) correlation(self.que.exp_dist_arrive, m, d) def btn_scatter_clicked(self): scatter_plot(self.que.exp_dist_arrive) def btn_bar_graph_2_clicked(self): bar_graph(self.que.exp_dist_prc, float(self.ui.middleProcTime.text())) def btn_correlation_2_clicked(self): m, d = estimates(self.que.exp_dist_arrive) correlation(self.que.exp_dist_prc, m, d) def btn_scatter_2_clicked(self): scatter_plot(self.que.exp_dist_prc) def change_radio_btn(self): if self.ui.radioButtonTask.isChecked(): self.ui.taskCounter.setEnabled(True) self.ui.timeCounter.setEnabled(False) else: self.ui.taskCounter.setEnabled(False) self.ui.timeCounter.setEnabled(True) def plots(self): figure, (ax1, ax2) = plt.subplots(2, 1) ax1.plot(self.que.cur_task_in_queue, color='#f3a870') ax1.set_title('Количество заявок в очереди') ax2.plot([ self.que.cur_task_in_queue[i] + self.dev.cur_task_in_dev[i] for i in range(len(self.que.cur_task_in_queue)) ], color='#243580') ax2.set_title('Количество заявок в системе') plt.show() def avr_plots(self): figure, (ax1, ax2) = plt.subplots(2, 1) ax1.plot(self.que.avr_cur_task_in_queue, color='#f3a870') ax1.set_title('Среднее количество заявок в очереди') ax2.plot([ self.que.avr_cur_task_in_queue[i] + self.dev.avr_cur_task_in_dev[i] for i in range(len(self.que.avr_cur_task_in_queue)) ], color='#243580') ax2.set_title('Среднее количество заявок в системе') plt.show() def coefficient_plots(self): figure, ax = plt.subplots(1, 1) ax.plot(self.dev.coefficients_dev, color='#eb5967') ax.set_title('Коэффициент использования системы') plt.show()
class RegExpTestGui(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.run_button_.clicked.connect(self.loadRegExp) def loadRegExp(self): #self.ui.result_text_browser_.setText("Yeah\nClicked") regexp_pattern = self.ui.regex_line_edit_.text() check_text = self.ui.check_text_line_edit_.text() if regexp_pattern.isEmpty(): message_list = qt_core.QStringList() message_list << "<font color=\"red\">Failed</font>" message_list << "RegExp field is empty." message_list << "Nothing to do." self.ui.result_text_browser_.setHtml(message_list.join("<br>")) elif check_text.isEmpty(): message_list = qt_core.QStringList() message_list << "<font color=\"red\">Failed</font>" message_list << "CheckText field is empty." message_list << "Nothing to do." self.ui.result_text_browser_.setHtml(message_list.join("<br>")) else: self.ui.result_text_browser_.setText("Ready to go") regexp = re.compile(str(regexp_pattern)) full_matches = qt_core.QStringList() captures = qt_core.QStringList() pos = 0 while True: match = regexp.match(check_text, pos) if match is None: break pos = match.end(0) + 1 full_matches << match.group(0) for capture in match.groups(0): captures << capture if full_matches.count() == 0: message_list = qt_core.QStringList() message_list << "<font color=\"red\">Failed</font>" message_list << "RegExp does not match CheckText" self.ui.result_text_browser_.setHtml(message_list.join("<br>")) else: message_list = qt_core.QStringList() message_list << "<font color=\"green\">Success</font>" message_list << "RegExp matches CheckText" if full_matches.count() is 1: message_list << qt_core.QString( "There is 1 full text match") else: message_list << qt_core.QString( "There are %1 full text matches").arg( full_matches.count()) message_list << "\"" + full_matches.join("\"<br>\"") + "\"<br>" if full_matches.count() is 0: message_list << qt_core.QString("There are no captures") elif full_matches.count() is 1: message_list << qt_core.QString("There is 1 capture") else: message_list << qt_core.QString( "There are %1 captures").arg(captures.count()) message_list << "\"" + captures.join("\"<br>\"") + "\"<br>" self.ui.result_text_browser_.setHtml(message_list.join("<br>"))
class PlotBuildApplication(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.centralWidget.setLayout(self.ui.plotArea) self.plot = Oscillator(self.ui.centralWidget) self.ui.plotArea.addWidget(self.plot) self.const_dialog = ConstDialog(self) self.set_dialog_const() self.connect(self.ui.constEditAction, SIGNAL('activated()'), self.edit_constant_slot) self.connect(self.ui.calculateAction, SIGNAL('activated()'), self.draw_plot_slot) self.connect(self.ui.saveImageAction, SIGNAL('activated()'), self.save_plot_image_slot) self.connect(self.const_dialog.ui.applyButton, SIGNAL('clicked()'), self.apply_const_slot) self.connect(self.const_dialog.ui.resetButton, SIGNAL('clicked()'), self.reset_const_slot) def const_init(self): self.plot.init_default_params() def set_dialog_const(self): cd = self.const_dialog.ui for key, value in self.plot.params.items(): field = getattr(cd, key) field.setValue(value) cd.scaleX.setValue(self.plot.scale_x) cd.scaleY.setValue(self.plot.scale_y) cd.showGrid.setChecked(True) for plot in self.plot.plots.values(): for line_name in plot.lines.keys(): if hasattr(cd, line_name): checkbox = getattr(cd, line_name) checkbox.setChecked(plot.lines[line_name]['enabled']) #===================================Слоты==================================== def draw_plot_slot(self): self.plot.start_animated_draw() def apply_const_slot(self): cd = self.const_dialog.ui self.plot.set_scale_x(cd.scaleX.value()) self.plot.set_scale_y(cd.scaleY.value()) self.plot.set_grid(cd.showGrid.isChecked()) for key, value in self.plot.params.items(): field = getattr(cd, key) value = field.value() self.plot.params[key] = value if cd.lineType.isChecked(): self.plot.set_draw_type('lines') elif cd.pointType.isChecked(): self.plot.set_draw_type('points') for plot in self.plot.plots.values(): for line_name in plot.lines.keys(): if hasattr(cd, line_name): checkbox = getattr(cd, line_name) plot.lines[line_name]['enabled'] = checkbox.isChecked() self.plot.start_animated_draw() def reset_const_slot(self): self.const_init() self.set_dialog_const() self.plot.start_animated_draw() def edit_constant_slot(self): self.set_dialog_const() self.const_dialog.show() def save_plot_image_slot(self): path = QtGui.QFileDialog.getExistingDirectory() if path: self.plot.save_plots(path)
class ApplicationWindow(QMainWindow): def __init__(self): super(ApplicationWindow, self).__init__() self.inited = False self.ui = Ui_MainWindow() self.ui.setupUi(self) try: with open('style.qss', 'r', encoding='utf-8') as f: self.setStyleSheet(f.read()) except: pass bind_host, bind_port = qt_get_host_port(self, '0.0.0.0', 22321) if bind_host is None or bind_port is None: return self.user = User(bind_host, bind_port, 'MagHSK') self.serverModel = ListTableModel(['uuid', 'host', 'port']) self.ui.serverTable.setModel(self.serverModel) self.blogModel = ListTableModel(['date', 'id', 'text']) self.ui.blogTable.setModel(self.blogModel) self.ui.refreshBlogButton.clicked.connect(self.refreshBlogButtonAction) self.ui.detailButton.clicked.connect(self.detailButtonAction) self.ui.subscribeButton.clicked.connect(self.subscribeButtonAction) self.ui.unsubscribeButton.clicked.connect(self.unsubscribeButtonAction) self.ui.updateButton.clicked.connect(self.updateButtonAction) self.ui.keywordButton.clicked.connect(self.keywordButtonAction) self.ui.refreshServerButton.clicked.connect( self.refreshServerButtonAction) self.ui.clearButton.clicked.connect(self.clearButtonAction) self.select_server = None self.select_blog = None self.client_thread = ClientThread(self) self.client_thread.serverUpdated.connect(self.refreshServer) self.client_thread.blogUpdated.connect(self.refreshBlog) self.client_thread.start() self.inited = True def clearButtonAction(self): try: confirm = QMessageBox.question(self, '请确认', '确认删除所有内容吗?') print(confirm) if confirm == QMessageBox.Yes: self.clearAll() except: traceback.print_exc() def clearAll(self): self.user.mblog_dict = {} self.refreshBlog() def refreshBlogButtonAction(self): try: self.user.positive_ask_blog() self.refreshBlog() except: traceback.print_exc() def detailButtonAction(self): try: row = self.getTableSelectedRow(self.ui.blogTable, len(self.blogModel.table)) print(row) if row is not None: date, blog_id, text = self.blogModel.table[row] subwindow = QDialog(self) dialog = Ui_Dialog() dialog.setupUi(subwindow) dialog.IDLabel.setText(str(blog_id)) dialog.blogContentEdit.setPlainText(text) subwindow.setWindowTitle("微博发表日期:" + date) subwindow.exec_() print('[** DEBUG **] Sub window return:', subwindow.result()) if subwindow.result() == QDialog.Accepted: self.user.mblog_dict[int(blog_id)][ 'text'] = dialog.blogContentEdit.toPlainText() self.refreshBlog() except: traceback.print_exc() def updateButtonAction(self): try: topic = self.ui.updateEdit.text().strip().split() row = self.getTableSelectedRow(self.ui.serverTable, len(self.serverModel.table)) if row is not None: server_uuid = self.getServerUUIDbyRow(row) if server_uuid is not None: self.user.send_topic_list(server_uuid, topic) except: traceback.print_exc() def keywordButtonAction(self): try: kwds = self.ui.keywordEdit.text().strip().split() row = self.getTableSelectedRow(self.ui.serverTable, len(self.serverModel.table)) if row is not None: server_uuid = self.getServerUUIDbyRow(row) if server_uuid is not None: mblog, topic = self.user.keyword_query(server_uuid, kwds) if mblog: blog_id, text = int(mblog['id']), mblog['text'] subwindow = QDialog(self) dialog = Ui_Dialog() dialog.setupUi(subwindow) dialog.IDLabel.setText(str(blog_id)) dialog.blogContentEdit.setPlainText(text) subwindow.setWindowTitle("类别:" + topic) subwindow.exec_() print('[** DEBUG **] Sub window return:', subwindow.result()) if subwindow.result() == QDialog.Accepted: mblog['text'] = dialog.blogContentEdit.toPlainText( ) self.user.mblog_dict[int(blog_id)] = mblog self.refreshBlog() pass else: alert = QMessageBox(parent=self) alert.setText('No such blog match your keywords.') alert.exec_() except: traceback.print_exc() def getServerUUIDbyRow(self, row): if row < len(self.serverModel.table): try: server_uuid = uuid.UUID(self.serverModel.table[row][0]) except Exception as e: alert = QMessageBox(parent=self) alert.setText('UUID invalid!') alert.exec_() return None print('You selected UUID', str(server_uuid)) return server_uuid return None def getTableSelectedRow(self, target, maximum): lst = target.selectedIndexes() if len(lst) == 1: row = lst[0].row() if row < maximum: print('You selected row', row) return row pass alert = QMessageBox(parent=self) alert.setText('Please select exactly one server!') alert.exec_() return None def unsubscribeButtonAction(self): try: row = self.getTableSelectedRow(self.ui.serverTable, len(self.serverModel.table)) if row is not None: server_uuid = self.getServerUUIDbyRow(row) print(server_uuid) if server_uuid is not None: self.user.logout(server_uuid) pass del self.serverModel.table[row] self.ui.serverTable.model().layoutChanged.emit() except: traceback.print_exc() pass def refreshServer(self): self.serverModel.table = [ (str(server), v[0], v[1]) for server, v in self.user.server_dict.items() ] self.ui.serverTable.model().layoutChanged.emit() def refreshBlog(self): print('Refresh blog!') self.blogModel.table = [ (mblog['time'], str(blog_id), mblog['text']) for blog_id, mblog in self.user.mblog_dict.items() ] self.ui.blogTable.model().layoutChanged.emit() def refreshServerButtonAction(self): try: self.refreshServer() except: traceback.print_exc() def subscribeButtonAction(self): try: host, port = qt_get_host_port(self, '127.0.0.1', 23432) if host is None or port is None: return server_uuid = self.user.register((host, port)) if server_uuid is not None: self.serverModel.table.append((str(server_uuid), host, port)) self.ui.serverTable.model().layoutChanged.emit() else: alert = QMessageBox(parent=self) alert.setText('Register failed!') alert.exec_() except: traceback.print_exc() def receiveNewBlogs(self, mblog_list): for mblog in enumerate(mblog_list): self.user.mblog_dict[mblog['id']] = mblog