コード例 #1
0
    def show_records(self):
        #         createDBConnection()
        query = QSqlQuery()
        try:
            emp_id_txt = self.ln_ID.text()
        except:
            pass

        if emp_id_txt:
            emp_id = int(emp_id_txt)
            query.prepare(
                "SELECT emp_id, name, Designation, dob from employee1 where emp_id = (:emp_id) "
            )
            query.bindValue(":emp_id", emp_id)

            if query.exec_():
                print("show_records Successful")

    #             self.lb_msg.SetText("showing current record !! ")
            else:
                print("show_records Error: ", query.lastError().text())
                model = QSqlTableModel()
                self.show_records_View("Title", model)
            while query.next():
                print("query show_records ", query.value(0), query.value(1),
                      query.value(2), query.value(3))
        else:
            QMessageBox.critical(self, 'Error', 'Please Enter Associate ID',
                                 QMessageBox.Retry)
            self.ln_ID.setFocus()
コード例 #2
0
 def updateCurrentActivity(self):
     if self.currentActivityId==-1:
         QMessageBox.critical(self, tr('Missing target'), tr('Current record is not associated with any existing record! Click Add or select Activity Record.\nSelecting an activity record will reset current values'))
         return
     desc     = str(self.activityDescription.text())
     duration = float(str(self.eventDuration.text()))
     rh       = float(str(self.relativeHumidity.text()))
     Tab      = float(str(self.ambientTemperature.text()))
     velOfAir = float(str(self.velocityOfAir.text()))
     metabolicActivity =str(self.metabolicActivity.text())
     clothingFile = str(self.clothingFile.text())
     radiationFluxFile = str(self.radiationFluxFile.text())
     activity = dict()
     activity['description'] = desc
     activity['duration'] = duration
     activity['rh'] = rh
     activity['Tab'] = Tab
     activity['velocityOfAir'] = velOfAir
     activity['metabolicActivity'] = metabolicActivity
     activity['clothingFile'] = clothingFile
     activity['radiationFluxFile'] = radiationFluxFile
     activity['id'] = self.currentActivityId  
     self.activities[self.currentActivityId] = activity
     self.activityButtons[self.currentActivityId].setText(desc)
     self.refreshGraph()  
コード例 #3
0
def log_uncaught_exceptions(ex_cls, ex, tb):
    text = '{}: {}:\n'.format(ex_cls.__name__, ex)
    import traceback
    text += ''.join(traceback.format_tb(tb))

    print(text)
    QMessageBox.critical(None, 'Error', text)
    quit()
コード例 #4
0
ファイル: main.py プロジェクト: skeptycal/iv
 def excepthook(self, exctype, value, traceback):
     if exctype == KeyboardInterrupt:
         return
     sys.__excepthook__(exctype, value, traceback)
     try:
         msg = str(value)
     except Exception:
         msg = repr(value)
     QMessageBox.critical(self, _('Unhandled error'), msg)
コード例 #5
0
 def _validate_monkeys(self):
     first_month = Monkey.unslash(self.ui.firstMonthEdit.text())
     last_month = Monkey.unslash(self.ui.lastMonthEdit.text())
     if not Monkey.is_valid_pair(first_month, last_month):
         msg = 'Invalid time frame: invalid month or first month after last month!'
         QMessageBox.critical(QMessageBox(), 'Input Error', msg)
         self.ui.firstMonthEdit.setFocus()
         return None
     return TimeInterval(first_month=first_month, last_month=last_month)
コード例 #6
0
    def closeEvent(self, event):

        boolFinished = self.qThreadObj.isFinished()
        if boolFinished == True:
            event.accept()
        else:
            QMessageBox.critical(self,"请等待!", ("等待任务完成!"))
            event.ignore()
        pass
コード例 #7
0
 def render_process_terminated(self, termination_type, exit_code):
     if termination_type == QWebEnginePage.CrashedTerminationStatus:
         QMessageBox.critical(
             self.parent(), _('Render process crashed'),
             _('The render process crashed while displaying the images with exit code: {}'
               ).format(exit_code))
     elif termination_type == QWebEnginePage.AbnormalTerminationStatus:
         QMessageBox.critical(
             self.parent(), _('Render process exited'),
             _('The render process exited while displaying the images with exit code: {}'
               ).format(exit_code))
コード例 #8
0
 def _save_clicked(self):
     rec = self._valid_emp()
     if rec:
         try:
             rec.save()
         except AllocatException as e:
             QMessageBox.critical(QMessageBox(), 'Input Error', e.msg)
             self.ui.nameEdit.setFocus()
             return
         Dataset.employees = Employee.get_all()
         self._load_list(Dataset.employees.keys(), rec.name)
     self.ui.addBtn.setEnabled(True)
コード例 #9
0
    def judge(self):
        user_name = self.lineEdit.text()  #获取用户名
        user_password = self.lineEdit_2.text()  #获取密码
        print(user_name, user_password)

        #如果用户名和密码分别是admin和123456,
        #判断密码帐号是否正确,正确就会打开hello窗口,并且关闭登录框,如果不对,则会弹出警告框。
        if user_name == 'admin' and user_password == '123456':

            hello_ui.show()
            ui.close()
        else:
            QMessageBox.critical(self, '警告', '用户名或者密码错误')
コード例 #10
0
    def sTimeToDateTime(self, inTime):  # convert time from string to datetime object
        # inTime: '13:43:02:578' string type
        # outTime: 2018-01-01 13:43:02.578000  datetime object

        # '2018 ' + startTime, '%Y %H:%M:%S'
        #itime = inTime[:8] + "." + inTime[10:12]   # convert 13:43:02:578 to 13:43:02.578
        # add date (2018-01-01)to the TIME for the sake of format of datetime class. could use real date of the data created
        try:
            outTime = datetime.strptime('2018 ' + inTime, '%Y %H:%M:%S:%f')  # convert the time from string to the datetime format
        except Exception as e:
            QMessageBox.critical(self, "Error", "TIME format error.\n" + e.__str__())
            outTime = datetime.now()
        return outTime
コード例 #11
0
    def login_check(self):
        name_hexdigest = SHA256.new(self.UserName.text().encode()).hexdigest()
        password_hexdigest = SHA256.new(
            self.Password.text().encode()).hexdigest()
        for i in self.login_info:
            if name_hexdigest == i['username']:
                if password_hexdigest == i['password']:
                    self.accept()
                else:
                    QMessageBox.critical(self, '登录异常', '密码错误!')
                break

        else:
            QMessageBox.critical(self, '登录异常', '用户名不存在!')
コード例 #12
0
    def load_images_from_directory(self):
        '''Charge les images '*.png' contenue dans le répertoire
           des images choisi avec un sélecteur graphique.'''

        # Choix du répertoire avec un sélecteur de fichier :
        dname = QFileDialog.getExistingDirectory(None,
                                                 'Choisir un dossier images',
                                                 self.mw.image_dir)
        if dname != '':
            # un répertoire valide a été choisi :
            self.video_path = None
            self.images_dir = dname + "/"

            try:
                # Lecture du fichier ascii des méta-données
                with open(self.images_dir + "metaData.txt", "r") as F:
                    data = F.read()
                exec('self.dico_video = ' + data)
            except:
                rep = QMessageBox.critical(
                    None,             # widget parent de QMessageBox
                    'Erreur',    # bandeau de la fenêtre
                    'Pas de fichier de méta-données dans le répertoire'+\
                    ' <{}>'.format(os.path.basename(dname)),
                    QMessageBox.Ok)
                return

            print("méta données :", self.dico_video)

            self.parse_meta_data()
            self.setTextInfoVideoGrid()

            # Mettre à jour l'application avec les nouvelles images chargées :
            self.update_images()
コード例 #13
0
def play(path, start_sec=0, end_sec=0):
    logger.info("mplayer interface in: %s" % path)
    global mplay_readiness_state
    if mplay_readiness_state == 'failed and notified':
        completed_play_notice.set()
        return completed_play_notice
    elif mplay_readiness_state == 'tried and failed':
        QMessageBox.critical(
            None, 'Mplayer Missing!', 'Cannot open mplayer. \n'
            'Have you installed mplayer?\n'
            '(On Windows, you can copy mplayer.exe '
            'from 2.1.26- anki installation)')
        completed_play_notice.set()
        mplay_readiness_state = 'failed and notified'
        return completed_play_notice
    queueMplayer(path, start_sec, end_sec)
    return completed_play_notice
コード例 #14
0
    def ExportDataToFile(self):
        if not self.tblreviewdata.selectedIndexes(): return  # no selection
        file_out = self.qleFilePath_out.text()
        if file_out[-4:].upper() != '.TXT': return
        strTestData = self.processData(
        )  # process the data by selection of time, rate...

        try:
            strTestData.data.to_csv(file_out, sep="\t", index=False)

        except Exception as e:
            QMessageBox.critical(
                self, "Error",
                "Error in writing data to file.\n" + e.__str__())

        self.progressBar.setValue(100)
        QMessageBox.information(self, "Export",
                                "Wrote data to file successfully.")
コード例 #15
0
 def load_databases(self, parent):
     '''
     load the database name list and append into combolist
     '''
     if not self.__database_driver:
         QMessageBox.warning(self, 'Warning', "Invalid database driver, please check.", QMessageBox.Ok)
         return
         
     result, database_list, message = self.__database_driver.get_database_list()
     if not result:
         QMessageBox.critical(self, 'Error', message, QMessageBox.Ok)
     else:
         if len(database_list) > 0:
             parent.addItem("")
             for name in database_list:
                 parent.addItem(name)
         else:
             QMessageBox.warning(self, 'Warning', "Database is empty.", QMessageBox.Ok)
コード例 #16
0
ファイル: textpane.py プロジェクト: TwoManyHats/GuiScannos
 def load(self, f):
     """Load file with name f. If succuss, return True. Otherwise, return False."""
     if not os.path.isfile(f):
         return False
     self.encoding = None
     try:
         data = open(f, encoding="utf_8").read()
         self.encoding = "utf_8"
     except:
         try:
             data = open(f, encoding="latin_1").read()
         except:
             pass
         self.encoding = "latin_1"
     if not self.encoding:
         s = "Failed to open {}. File is not UTF-8 or Latin-1.".format(f)
         QMessageBox.critical(self, "File Error", s)
         return False
     self.setPlainText(data)
     return True
コード例 #17
0
 def save_tikz(sel, *args):
     dialog = QFileDialog()
     dialog.setDefaultSuffix(".tex")
     result = dialog.getSaveFileName(self,
                                     QCoreApplication.translate(
                                         "side_widget",
                                         "Save TikZ Output"),
                                     filter="LaTex (*.tex)")
     if result[0]:
         try:
             self.__io_controller.generate_tikz(result[0])
         except Exception:
             logger.exception("Exception while saving tikz")
             box = QMessageBox()
             box.critical(
                 self,
                 QCoreApplication.translate("side_widget", "Error"),
                 QCoreApplication.translate(
                     "side_widget", "Error while writing "
                     "tikz file. "
                     "See log for details."))
コード例 #18
0
 def _save_clicked(self):
     interval = self._validate_monkeys()
     if not interval:
         return
     rec = Project([
         self.current_rec_id,
         self.ui.nicknameEdit.text(),
         self.ui.nameEdit.text(),
         interval.first_month,
         interval.last_month,
         self.ui.notesEdit.toPlainText(),
         self.ui.billingEdit.toPlainText()
     ])
     try:
         rec.save()
     except AllocatException as e:
         QMessageBox.critical(QMessageBox(), 'Input Error', e.msg)
         self.ui.nameEdit.setFocus()
         return
     Dataset.projects = Project.get_all()
     self._load_list(Dataset.projects.keys(), rec.nickname)
     self.ui.addBtn.setEnabled(True)
コード例 #19
0
ファイル: views.py プロジェクト: ehmoussi/asterstudy
    def importFile(self):
        """
        Called when 'Import from file' button is clicked.

        Allows to select file and fills in a table if any file was given.
        """
        data = None
        title = translate("ParameterPanel", "Import table")
        filters = common_filters()
        filename = get_file_name(mode=1,
                                 parent=self.table,
                                 title=title,
                                 url="",
                                 filters=filters,
                                 dflt_filter=filters[2])  # "Text files"
        if filename:
            try:
                data = numpy.loadtxt(filename, delimiter=',')
            except BaseException as exc:
                QMessageBox.critical(self.table, "AsterStudy", exc.message)
            else:
                self.setData(data)
コード例 #20
0
ファイル: mainShop4.py プロジェクト: jgt69/python
def editar_item(id_editar):
    QMessageBox.critical(MainWindow, "AVISO", "Se va a editar el ID: " + str(id_editar))

    ui_editar.setupUi(MainWindow)

    item_a_editar = obtener_item_por_id(id_editar)

    index = ui_editar.cbx_tipo.findText(item_a_editar.tipo, QtCore.Qt.MatchFixedString)

    # RadioButtons
    if item_a_editar.gama == 'Basic':
        ui_editar.rbn_basic.setChecked(True)

    if item_a_editar.gama == 'Advance':
        ui_editar.rbn_advance.setChecked(True)

    if item_a_editar.gama == 'Elite':
        ui_editar.rbn_elite.setChecked(True)

    ui_editar.cbx_tipo.setCurrentIndex(index)

    ui_editar.txt_marca.setText(item_a_editar.marca)
    ui_editar.txt_modelo.setText(item_a_editar.modelo)
    ui_editar.txt_precio.setText(str(item_a_editar.precio).replace('.', ','))

    # Checkbox
    if item_a_editar.soporte == 1:
        ui_editar.chk_premium.setChecked(True)

    # Recuperar imagen en la ventana editar
    pixmap = QPixmap('img_catalog/' + str(item_a_editar.id) + '.jpg')
    ui_editar.lbl_imagen.setPixmap(pixmap)

    ui_editar.btn_seleccionar_archivo.clicked.connect(cambiar_imagen)

    ui_editar.btn_cancel.clicked.connect(mostrar_table)

    ui_editar.btn_editar.clicked.connect(partial(guardar_cambios_item, item_a_editar.id))
コード例 #21
0
    def add_records(self):

        emp_id = self.ln_ID.text()
        name = self.ln_Name.text()
        designation = self.ln_Desig.text()
        dob = self.lbl.text()

        #             createDBConnection()
        query = QSqlQuery()
        query.prepare("INSERT INTO employee1 (emp_id, name, designation, dob) "
                      "VALUES (:emp_id, :name, :designation, :dob)")

        query.bindValue(":emp_id", emp_id)
        query.bindValue(":name", name)
        query.bindValue(":designation", designation)
        query.bindValue(":dob", dob)

        try:
            if query.exec_():
                #                 add_msg = "Row Added"
                #                 self.lb_msg.setText(add_msg)
                print("add_records Successful")
                QMessageBox.information(self, 'Info', 'Row Added',
                                        QMessageBox.Ok)
                #                 self.show_records()
                self.clr_records()

            else:
                err_text = query.lastError().text()
                print("add_records Error: ", err_text)
                QMessageBox.critical(self, 'Error', err_text,
                                     QMessageBox.Retry)
#                 fail_msg = "Insert Failed !! "
#                 self.lb_msg.SetText(fail_msg)
        except:
            pass
コード例 #22
0
 def _valid_emp(self):
     name = self.ui.nameEdit.text()
     if not Employee.is_valid_name(name):
         msg = 'Employee name is invalid'
         QMessageBox.critical(QMessageBox(), 'Input Error', msg)
         self.ui.nameEdit.setFocus()
         return None
     grade = self.ui.gradeEdit.text()
     if not Employee.is_valid_grade_step(grade):
         msg = 'Employee grade is invalid'
         QMessageBox.critical(QMessageBox(), 'Input Error', msg)
         self.ui.gradeEdit.setFocus()
         return None
     step = self.ui.stepEdit.text()
     if not Employee.is_valid_grade_step(step):
         msg = 'Employee step is invalid'
         QMessageBox.critical(QMessageBox(), 'Input Error', msg)
         self.ui.stepEdit.setFocus()
         return None
     fte = self.ui.fteEdit.text()
     if not Employee.is_valid_fte(fte):
         msg = 'Employee FTE is invalid'
         QMessageBox.critical(QMessageBox(), 'Input Error', msg)
         self.ui.fteEdit.setFocus()
         return None
     cp = '015' if self.ui.cp15Button.isChecked() else '016'
     investigator = self.ui.investigatorBox.isChecked()
     notes = self.ui.notesEdit.toPlainText()
     return Employee([
         self.cur_rec_id,
         name,
         int(grade),
         int(step),
         int(fte),
         cp,
         investigator,
         notes
     ])
コード例 #23
0
ファイル: mainShop4.py プロジェクト: jgt69/python
def guardar_cambios_item(id_guardar):
    guardar_new_item = Periferico()
    guardar_new_item.id = id_guardar
    guardar_new_item.tipo = ui_editar.cbx_tipo.currentText()

    # Validación de los QLineEdit
    guardar_new_item.marca = ui_editar.txt_marca.text()
    if not validar_marca(guardar_new_item.marca):
        QMessageBox.critical(MainWindow, "Error", "La marca introducida es incorrecta")
        return

    guardar_new_item.modelo = ui_editar.txt_modelo.text()
    if not validar_modelo(guardar_new_item.modelo):
        QMessageBox.critical(MainWindow, "Error", "El modelo introducido es incorrecto")
        return

    guardar_new_item.precio = ui_editar.txt_precio.text().replace(",", ".")
    if not validar_precio(guardar_new_item.precio):
        QMessageBox.critical(MainWindow, "Error", "La cantidad introducida no es válida")
        return

    # RadioButtons
    if ui_editar.rbn_basic.isChecked():
        guardar_new_item.gama = "Basic"

    if ui_editar.rbn_advance.isChecked():
        guardar_new_item.gama = "Advance"

    if ui_editar.rbn_elite.isChecked():
        guardar_new_item.gama = "Elite"

    # Checkbox
    if ui_editar.chk_premium.isChecked():
        guardar_new_item.soporte = True

    #  Selección de la imagen, si no ha cambiado se mantiene la existente
    temporal = 'temp/image.jpg'
    if Path(temporal).is_file():
        ruta_destino = 'img_catalog/' + str(id_guardar) + '.jpg'
        shutil.move('temp/image.jpg', ruta_destino)

    guardar_cambios_producto(guardar_new_item)

    QMessageBox.about(MainWindow, "Información", "Se guardaron los cambios en el registro con ID: " + str(id_guardar))

    mostrar_table()
コード例 #24
0
    def check_input(self, url, path_name):
        '''检查用户输入
        :param url: 用户填写的下载url
        :param path_name: 用户填写的本地保存路径
        '''

        if url.isspace() or url == '':
            QMessageBox.critical(self, "错误", "请填写下载网址!", QMessageBox.Retry)
            return False
        elif not 'https://huaban.com' in url:
            QMessageBox.critical(self, "错误", "请检查网址\n此软件目前仅支持花瓣网!",
                                 QMessageBox.Retry)
            return False
        elif path_name.isspace() or path_name == '':
            QMessageBox.critical(self, "错误", "请填写保存路径!", QMessageBox.Retry)
            return False
        else:
            return True
コード例 #25
0
ファイル: main.py プロジェクト: cro-ki/pypog
 def error_handler(typ, value, trace):
     QApplication.restoreOverrideCursor()
     QMessageBox.critical(iface, typ.__name__, "{}".format(value))
     SYS_HOOK(typ, value, trace)
コード例 #26
0
    def plotData(self, plotItem, selectedItems):
        '''selectedItems: items selected in tree view
           dfData: data frame of the selected data
        '''

        #plotItem = self.dataPlot.plotItem

        # viewbox = pg.ViewBox()
        # plotItem.scene().addItem(viewbox)

        #plotItem = self.currSelctPlotWgt
        plotItem.addLegend()

        #plotItem.getAxis('bottom').setPen(pg.mkPen(color='#000000', width=1))
        i = 0
        for iItem in selectedItems:
            if iItem.parent():     # not the root item
                filename = iItem.parent().text(1)    # get the parent item name - filename

                for iData in self.lTestDATA:          # find out the data from the data frame list by the filename
                    if filename == iData.fileName:
                        dfData = iData.data
                        break                       # break out of the loop for data


                data_head = iItem.text(1)           # get the column name of data for plotting
                curve_name = data_head + '>>' + iItem.text(2) + '>>' + iItem.text(3)    # parameter/parameter desc/unit

                # y axis
                data_2_plot = list(dfData[data_head])

                # get the list of time column, for x axis
                sTime = list(dfData['TIME'])

                # convert the time in string to date time object
                iTime = [self.sTimeToDateTime(j) for j in sTime]

                i += 1  # for color index use

                # example
                # pw.plot(x=[x.timestamp() for x in iTime ], y= list(df['BCVIIN']), pen = 'r')
                try:
                    plotcurve = PlotCurveItem(x=[x.timestamp() for x in iTime], y= data_2_plot, name = curve_name, pen=self.colorDex[i%5])
                    plotItem.addItem(plotcurve)
                except Exception as e:
                    QMessageBox.critical(self, "Error", "Error with data to plot.\n" + e.__str__())

                if not self.bPlotted:
                    self.bPlotted = True
                plotWgtName = self.currSelctPlotWgt.getViewBox().name
                if not plotWgtName: print("check the plotwidget definition in the mainUI.py, comment it!!!!")
                self.lPlottedItems.append({'Plot': plotWgtName, 'Curvename': curve_name, 'Filename': filename })
                self.listWidget.addItem(plotWgtName + '||' + curve_name + '||' + filename )

                # labl = QLabel(curve_name)
                # plotItem.addItem(labl)

                for lgditem in plotItem.scene().items():  # remove the legend
                    if isinstance(lgditem, graphicsItems.LegendItem.ItemSample):  #
                        lgditem.hide()   # hide the sample of legend  # plotItem.scene().items()[5].item is the curve itself
                        break

                self.autoRangeAllWins()
コード例 #27
0
ファイル: main.py プロジェクト: cjlux/VideoTracker
    def ImportCSV(self):
        '''Import Data from CSV file.'''

        # Lance un sélecteur de fichier pour choisir le fichier à écrire.'''
        fname = QFileDialog.getOpenFileName(self,
                                            'Choisir un nom de fichier CSV à importer',
                                            VideoTracker.csv_dir,
                                            'Fichier CSV (*.csv *.txt)')
        if fname[0] == "": return

        with open(fname[0], 'r', encoding="utf8") as F:
            data = F.readlines()

        if "VIDEOTRACKER MADE THIS FILE!" not in data[0]:
            rep = QMessageBox.critical(
                    None,        # QMessageBox parent widget
                    'Erreur',    # window bar
                    "Désolé, le fichier CSV <{}> n'a pas été\forgé par VideoTracker..."\
                    .format(os.path.basename(fname[0])), QMessageBox.Ok)
            return

        self.clearPlots()
        
        # Extract the meta-data dictionary and fill the field in the Image display:
        exec("self.imageTab.dico_video="+data[1].split('#')[1].strip())
        self.imageTab.parse_meta_data()
        self.imageTab.setTextInfoVideoGrid()

        # Extract the unit-scale dictionary and fill the field in the Image display:
        unit_data = data[2].split('#')[1].strip()
        exec("self.unit_dict={}".format(unit_data))
        print("self.unit_dict:",self.unit_dict)
        self.imageTab.scale_pixel.setText(str(self.unit_dict["pixels"]))
        self.imageTab.scale_mm.setText(str(self.unit_dict["mm"]))
        self.imageTab.scale_XY()
        self.imageTab.scaleInfoVisible(True)

        # Extract algo information:
        algo = data[3].split('#')[1].strip()
        try:
            index = ImageDisplay.algo_traj.index(algo)
        except:
            rep = QMessageBox.critical(
            None,        # QMessageBox parent widget
            'Erreur',    # window bar
            "L'information sur l'algorithme <{}> n'est pas reconnue".format(algo))
            return
        self.imageTab.btn_algo.setCurrentIndex(index)
        print('index:', index,
              'self.imageTab.btn_algo.currentText():',
              self.imageTab.btn_algo.currentText())
            
        # Extract RGB target color:
        RGB = data[4].split('#')[1].strip()
        print("self.target_RGB=np."+RGB)
        try:
            exec("self.target_RGB=np."+RGB)
        except:
            rep = QMessageBox.critical(
            None,        # QMessageBox parent widget
            'Erreur',    # window bar
            "L'information RGB <{}> n'est pas reconnue".format(RGB))
            return

        # Read the CSV file with pandas:
        self.csv_dataFrame = pandas.read_csv(fname[0],
                                             header=5,
                                             delimiter=';',
                                             encoding="utf8")
        data = self.csv_dataFrame.values
        data = [data[:,1], data[:,2], data[:,3]]
        self.target_pos = np.array(data)        
        self.imageTab.display_plots()

        # Clear display tab:
        self.imageTab.btn_algo.clear()
        self.imageTab.buttonsState(importCSV=True)
        self.imageTab.img_lbl.setPixmap(QPixmap())
        
        self.twoPlots_VxVy.reset()
コード例 #28
0
 def __show_error(self, message: str):
     box = QMessageBox()
     box.critical(self, "Error", message)
コード例 #29
0
 def message_error(self, message: str):
     QMessageBox.critical(self.widget(), "Photocopieuse", message)
コード例 #30
0
    def openDateFile(self):
        fname = QFileDialog.getOpenFileName(
            self, 'Open file',
            'C:\\onedrive\\OneDrive - Honeywell\\VPD\\test data\\_8hz_test_sample.txt',
            "Text Files (*.txt);;All Files (*)")
        if fname[0]:  # process only the one selection

            if self.sDataFilePath != fname[
                    0]:  # the file was not selected before
                self.setDataFilePath(fname[0])

                try:
                    sizeoffile = path.getsize(self.sDataFilePath)
                    if sizeoffile <= 0:
                        QMessageBox.critical(self, "Error",
                                             "Data rate should not be Zero")
                        return
                except Exception as e:
                    QMessageBox.critical(
                        self, "Error",
                        "Check the file's existence.\n" + e.__str__())
                    return

                try:
                    dfData = read_csv(
                        self.sDataFilePath,
                        delim_whitespace=True,
                        nrows=200,
                        error_bad_lines=False)  # read 200 rows only
                    #dfData['TIME']
                    self.iDataRate = self.estDataRate(list(dfData['TIME']))
                except Exception as e:
                    QMessageBox.critical(
                        self, "Error",
                        "Check the data format.\n" + e.__str__())
                    return

                if self.iDataRate <= 0:
                    QMessageBox.critical(self, "Error",
                                         "Data rate should not be Zero")
                    return

                try:
                    self.setDataRate()

                    self.qleFileSize.setText(str(round(
                        sizeoffile / 1024, 1)))  # KB, keep on digit of decimal

                    # read the first 10 rows from the file
                    self.data2review = dfData.head(int(
                        self.leRows.text()))  # leRows = for preview rows
                    self.dataHeader = list(dfData)  # data header list

                    self.startTime = dfData['TIME'].iloc[0][:8]
                    self.sStartTime = self.startTime  # default selected time is same as the data start time

                    self.teDataFromTime.setTime(
                        datetime.strptime('2018 ' + self.startTime,
                                          '%Y %H:%M:%S').time())
                    self.teFromTime.setTime(
                        datetime.strptime('2018 ' + self.startTime,
                                          '%Y %H:%M:%S').time())

                    self.qleColumns.setText(str(dfData.shape[1]))

                    self.iStartRow = self.firstRow
                    self.qleFromRow.setText(str(self.firstRow))
                except Exception as e:
                    pass
                    # print(e.__str__())
                try:
                    self.lastRow = self.estRowNum(self.sDataFilePath)
                    self.iEndRow = self.lastRow
                    self.qleRows.setText(str(self.lastRow))
                    self.qleToRow.setText(str(self.lastRow))
                except Exception as e:
                    print(e.__str__())

                try:
                    duration = round(
                        self.iEndRow / self.iDataRate
                    )  # estimate the seconds from row number and sample frequency
                    self.endTime = self.estTimeByDuration(
                        self.sStartTime, duration)
                    self.sEndTime = self.endTime
                    self.teDataToTime.setTime(
                        datetime.strptime('2018 ' + self.endTime,
                                          '%Y %H:%M:%S').time())
                    self.teToTime.setTime(
                        datetime.strptime('2018 ' + self.endTime,
                                          '%Y %H:%M:%S').time())
                except Exception as e:
                    print(e.__str__())
                    # do the time consuming work of scan the data file
                self.populatePreviewTable()
コード例 #31
0
ファイル: Login_ui.py プロジェクト: che7611/hseng_pyqt
 def login_check(self):
     # if self.ui.UserName.text() == 'hadrianl' and self.ui.Password.text() == '666666':
     if True:
         self.accept()
     else:
         QMessageBox.critical(self, '错误', '用户名或密码不匹配')
コード例 #32
0
 def unhandled_error(self, data):
     if False:  # disabled in case there is continuous looping error which can the dialog to popup infinitely
         QMessageBox.critical(self.parent(), _('Unhandled error'),
                              data['msg'])
コード例 #33
0
ファイル: mainShop4.py プロジェクト: jgt69/python
def registrar_periferico():
    periferico = Periferico()

    periferico.tipo = ui_registro.cbx_tipo.currentText()

    # Validating QlineEdit marca / modelo
    periferico.marca = ui_registro.txt_marca.text()
    if not validar_marca(periferico.marca):
        QMessageBox.critical(MainWindow, "Error", "La marca introducida es incorrecta")
        return

    periferico.modelo = ui_registro.txt_modelo.text()
    if not validar_modelo(periferico.modelo):
        QMessageBox.critical(MainWindow, "Error", "El modelo introducido es incorrecto")
        return

    # RadioButtons
    if ui_registro.rbn_basic.isChecked():
        periferico.gama = "Basic"

    if ui_registro.rbn_advance.isChecked():
        periferico.gama = "Advance"

    if ui_registro.rbn_elite.isChecked():
        periferico.gama = "Elite"

    # Validating QLineEdit precio
    periferico.precio = ui_registro.txt_precio.text()
    if not validar_precio(periferico.precio):
        QMessageBox.critical(MainWindow, "Error", "La cantidad introducida no es válida")
        return
    else:
        periferico.precio = periferico.precio.replace(",", ".")

    #  Select image
    id_info = registro_periferico(periferico)
    ruta_destino = 'img_catalog/' + str(id_info) + '.jpg'
    shutil.move('temp/image.jpg', ruta_destino)

    # Checkbox
    if ui_registro.chk_premium.isChecked():
        periferico.soporte = True

    # Reset LineEdit
    ui_registro.txt_marca.setText("")
    ui_registro.txt_modelo.setText("")
    ui_registro.txt_precio.setText("")

    # Reset ComboBox
    index = ui_registro.cbx_tipo.findText("Accessory", QtCore.Qt.MatchFixedString)
    ui_registro.cbx_tipo.setCurrentIndex(index)

    # Uncheck RadioButtons
    if ui_registro.rbn_basic.isChecked():
        ui_registro.rbn_basic.setChecked(False)

    if ui_registro.rbn_advance.isChecked():
        ui_registro.rbn_advance.setChecked(False)

    if ui_registro.rbn_elite.isChecked():
        ui_registro.rbn_elite.setChecked(False)

    # Uncheck Checkbox
    ui_editar.chk_premium.setChecked(False)

    ui_registro.lbl_imagen.clear()

    QMessageBox.about(MainWindow, "Info", "Registro OK")
コード例 #34
0
 def errorMessage(self, title, message):
     return QMessageBox.critical(self, title,
                                 '<p><b>%s</b></p>%s' % (title, message))
コード例 #35
0
    def processData(self):
        datafilename = path.basename(self.sDataFilePath)  # get the filename
        if datafilename:  # data file existing

            # get the selected column header
            dfData = read_csv(self.sDataFilePath,
                              delim_whitespace=True,
                              nrows=1,
                              error_bad_lines=False)  # read 1 line
            #header = list(dfData)    # get the header to a list

            selectedColumnHeader = ['TIME']

            # indexes = self.tblreviewdata.selectedIndexes()  # the indexes of current selections
            # for i in range (0, len(indexes), self.tblreviewdata.rowCount()):
            #     columnhead = list(dfData)[indexes[i].column()]  # get the selected column header

            indexes = self.tblreviewdata.selectionModel().selectedColumns(
            )  # the indexes of current selected columns

            for i in range(
                    0,
                    len(self.tblreviewdata.selectionModel().selectedColumns())
            ):  # get the column index number
                columnhead = list(dfData)[
                    indexes[i].column()]  # get the column header label
                if columnhead != 'TIME' and columnhead not in selectedColumnHeader:
                    selectedColumnHeader.append(
                        columnhead)  # add column header to the list

            if len(selectedColumnHeader) == 1:
                QMessageBox.warning(
                    self, 'Warning',
                    "Select at least one column other than 'TIME'!")
                return

        # read the data file with changed rate and selected columns

            dfData = read_csv(self.sDataFilePath,
                              delim_whitespace=True,
                              error_bad_lines=False,
                              iterator=True)

            if self.lastRow - self.iStartRow >= 2048:  # set chunk size to 2048 (2K rows) as standard size
                chunkSize = max(2048, self.iDataRate)
            else:
                chunkSize = min(2048, self.lastRow - self.iStartRow)
            chunks = []

            global rows_readover  # the row read over
            rows_readover = 0
            try:  # skip the rows if start from row 1 to iStartRow
                if self.iStartRow > chunkSize:  # the start rows > chunksize
                    for j in range(self.iStartRow // chunkSize):
                        dfData.get_chunk(chunkSize)
                        rows_readover += chunkSize
                        self.progressBar.setValue(
                            round(rows_readover / self.lastRow * 100))
                    dfData.get_chunk(self.iStartRow - rows_readover)
                else:
                    dfData.get_chunk(
                        self.iStartRow -
                        1)  # skip once for size of iStartRow, starting from 0
                rows_readover = self.iStartRow - 1  # the row read over
                self.progressBar.setValue(
                    round(rows_readover / self.lastRow * 100))

            except Exception as e:
                QMessageBox.critical(self, "Error", e.__str__())
                pass

            extract_row_range = range(
                0, chunkSize - 1, self.iDataRate // self.newRate
            )  # get the rows of newrate per the rows of data rate

            while True:
                try:
                    chunk = dfData.get_chunk(chunkSize)
                    chunkOfSelected = chunk[selectedColumnHeader]
                    if chunkOfSelected.shape[0] < len(
                            extract_row_range
                    ) * self.iDataRate // self.newRate:
                        extract_row_range = range(
                            0, chunkOfSelected.shape[0] - 1,
                            self.iDataRate // self.newRate)
                    chunkOfSelected = chunkOfSelected.iloc[
                        extract_row_range, :]
                    chunks.append(chunkOfSelected)
                    rows_readover += chunkSize
                    self.progressBar.setValue(
                        round(rows_readover / self.lastRow * 100))
                    if rows_readover > self.iEndRow: break
                except StopIteration:
                    self.progressBar.setValue(100)
                    print(
                        "data imported"
                    )  #QMessageBox.critical (self, "Error", 'Iteration is stopped')
                    break

            dfData = concat(chunks, ignore_index=True)

            # enclose the dfData into class clsTestData
            strTestData = clsTestData(datafilename)
            strTestData.header = selectedColumnHeader
            strTestData.column = dfData.shape[1]
            strTestData.row = dfData.shape[0]
            strTestData.rate = int(self.sbRate.text())
            strTestData.data = dfData

            return strTestData