Пример #1
0
    def showTempPasswordDialog(self):
        """ Sets overridePassword for a server.
        Using this one doesn't actually have to enter the password
        in the ServerDialog (and by extension save to disk).
        """
        serverList = ServerList()

        # Create a stringlist to be used by the qinputdialog
        stringList = []
        for server in serverList.getTable():
            stringList.append(server.name)

        # Display list of servers
        (serverString, ok) = QInputDialog.getItem(
            self,
            QApplication.translate("MainWindow", "Select server"),
            QApplication.translate("MainWindow", "Server:"),
            stringList,
            editable=False
        )
        if ok:
            server = serverList.getServerObjectByName(serverString)
            if server != None:
                # Ask for password
                (value, ok) = QInputDialog.getText(
                    self,
                    QApplication.translate("MainWindow", "Temporary password"),
                    QApplication.translate("MainWindow", "Enter password:"),
                    QLineEdit.Password
                )
                if ok:
                    # Use value as the overridePassword for the server.
                    LumaConnection(server).overridePassword(value)
Пример #2
0
 def insert_item(self):
     """Insert item"""
     index = self.currentIndex()
     if not index.isValid():
         row = self.model.rowCount()
     else:
         row = index.row()
     data = self.model.get_data()
     if isinstance(data, list):
         key = row
         data.insert(row, '')
     elif isinstance(data, dict):
         key, valid = QInputDialog.getText(self,
                           translate("DictEditor", 'Insert'),
                           translate("DictEditor", 'Key:'),
                           QLineEdit.Normal)
         if valid and not key.isEmpty():
             key = try_to_eval(unicode(key))
         else:
             return
     else:
         return
     value, valid = QInputDialog.getText(self,
               translate("DictEditor", 'Insert'),
               translate("DictEditor", 'Value:'),
               QLineEdit.Normal)
     if valid and not value.isEmpty():
         self.new_value(key, try_to_eval(unicode(value)))
Пример #3
0
def edit_layer_label(layer):
    """ Interactively edit a layer's label """
    dialog = QInputDialog()
    label, isok = dialog.getText(None, 'New Label:', 'New Label:',
                                 text=layer.label)
    if isok and str(label) != layer.label:
        layer.label = str(label)
Пример #4
0
    def callback_MocapRowEntry(self):
        # https://stackoverflow.com/questions/7907928/openpyxl-check-for-empty-
        global item
        global description
        global SuffixCount
        global rowCountIndex

        sheet = wb.get_sheet_by_name('Project 1')

        sheet['A'+str(rowCountIndex)].value = str(SuffixCount)
        sheet['B'+str(rowCountIndex)].value = 'MVN_Take_'+ str(SuffixCount)
        sheet['C'+str(rowCountIndex)].value = 'FBX_'+str(SuffixCount)+'.fbx'

        # for selecting which level the mocap was captured on #
        items = ('No-Level', 'Single-Level', 'Multi-Level')
        item, ok = QInputDialog.getItem(self, "Select Which Level", "Capture-Type", items, 0, False)
        if ok and item:
            sheet['D'+str(rowCountIndex)].value = str(item)

        # for entering the description for the mocap take #
        description, ok = QInputDialog.getText(self, "Take Description", "Enter a Description for this Take:")
        if ok and description:
            sheet['E'+str(rowCountIndex)].value = str(description)
            self.le_outputfield.setText('Entry '+ str(SuffixCount)+' Entered!')
        print('|| Entry: ' + str(SuffixCount) + ' | Level-Type: ' + str(item) + ' | Description: ' + str(description) + ' ||')

        SaveFile('template.xlsx')
        SuffixCount += 1
        rowCountIndex += 1
Пример #5
0
 def _getValue(self, title, label, valueType=QVariant.String, defaultValue='', minValue=0, maxValue=0, decimals=0):
     if valueType == QVariant.Double:
         return QInputDialog.getDouble(None, title, label, defaultValue, minValue, maxValue, decimals)
     elif valueType == QVariant.Int:
         return QInputDialog.getInt(None, title, label, defaultValue, minValue, maxValue)
     else:
         return QInputDialog.getText(None, title, label, text=defaultValue)
Пример #6
0
 def make_jss(self, html):
     ' make js '
     indnt = ' ' * int(QInputDialog.getInteger(None, __doc__,
                       " JS Indentation Spaces: ", 4, 0, 8, 2)[0])
     scrpt = QInputDialog.getItem(None, __doc__, "Enclosing script Tags ?",
                     ['Use script html tags', 'No script tags'], 0, False)[0]
     p = True if 'Use script html tags' in scrpt else False
     self.soup = self.get_soup(html)
     jss = '<script>{}'.format(linesep) if p is True else ''
     jss += '//{} by {}{}'.format(datetime.now().isoformat().split('.')[0],
                                    getuser(), linesep)
     jss += '$(document).ready(function(){' + linesep
     previously_styled = []
     previously_styled.append(tag_2_ignore)
     jss += '{}//{}{}'.format(linesep, '-' * 76, linesep)
     for part in self.get_ids():
         if part not in previously_styled:
             jss += '{}//{}{}'.format(indnt, '#'.join(part).lower(), linesep)
             jss += js_template.format(indnt, 'var ',
                    re.sub('[^a-z]', '', part[1].lower() if len(part[1]) < 11 else re.sub('[aeiou]', '', part[1].lower())),
                    ' = ', '$("#{}").lenght'.format(part[1]), ';', linesep,
                    linesep, '')
             previously_styled.append(part)
     jss += '//{}{}'.format('-' * 76, linesep)
     for part in self.get_classes():
         if part not in previously_styled:
             jss += '{}//{}{}'.format(indnt, '.'.join(part).lower(), linesep)
             jss += js_template.format(indnt, 'var ',
                    re.sub('[^a-z]', '', part[1].lower() if len(part[1]) < 11 else re.sub('[aeiou]', '', part[1].lower())),
                    ' = ', '$(".{}").lenght'.format(part[1]), ';', linesep,
                    linesep, '')
             previously_styled.append(part)
     jss += '});'
     jss += '{}</script>'.format(linesep) if p is True else ''
     return jss.strip()
Пример #7
0
    def showTempPasswordDialog(self):
        """ Sets overridePassword for a server.
        Using this one doesn't actually have to enter the password
        in the ServerDialog (and by extension save to disk).
        """
        serverList = ServerList()

        # Create a stringlist to be used by the qinputdialog
        stringList = []
        for server in serverList.getTable():
            stringList.append(server.name)

        # Display list of servers
        (serverString, ok) = QInputDialog.getItem(
            self,
            QApplication.translate("MainWindow", "Select server"),
            QApplication.translate("MainWindow", "Server:"),
            stringList,
            editable=False)
        if ok:
            server = serverList.getServerObjectByName(serverString)
            if server != None:
                # Ask for password
                (value, ok) = QInputDialog.getText(
                    self,
                    QApplication.translate("MainWindow", "Temporary password"),
                    QApplication.translate("MainWindow", "Enter password:"),
                    QLineEdit.Password)
                if ok:
                    # Use value as the overridePassword for the server.
                    LumaConnection(server).overridePassword(value)
Пример #8
0
 def _getValue(self, title, label, valueType=QVariant.String, defaultValue='', minValue=0, maxValue=0, decimals=0):
     if valueType == QVariant.Double:
         return QInputDialog.getDouble(None, title, label, defaultValue, minValue, maxValue, decimals)
     elif valueType == QVariant.Int:
         return QInputDialog.getInt(None, title, label, defaultValue, minValue, maxValue)
     else:
         return QInputDialog.getText(None, title, label, text=defaultValue)
Пример #9
0
    def __new_graph(self):

        if self.project is None:
            return

        graph, ok = QInputDialog.getText(
            self.__iface.mainWindow(),
            "Graph",
            "Graph name:",
            QLineEdit.Normal,
            "test_graph",
        )

        if not ok:
            return

        parent, ok = QInputDialog.getText(
            self.__iface.mainWindow(),
            "Parent Graph",
            "Parent Graph name:",
            QLineEdit.Normal,
            "",
        )

        if not ok:
            return

        self.project.new_graph(graph, parent)
        self.__current_graph.addItem(graph)
        self.__current_graph.setCurrentIndex(
            self.__current_graph.findText(graph))
Пример #10
0
    def add_display(self):
        analog_ports = self.home_module.client_core.get_analog_ports()

        (name, ok) = QInputDialog.getText(
            self,
            QCA.translate("AdminHomeMap", "Agregar Display"),
            QCA.translate("AdminHomeMap", "Ingresar el nombre del display:"),
        )

        if ok:
            if len(name) > 32 or len(name) < 3:
                QMessageBox.critical(
                    self,
                    QCA.translate("AdminHomeHeating", "Agregar Display"),
                    QCA.translate("AdminHomeHeating", "El nombre del display debe tener entre 3 y 32 caracteres"),
                )
            else:
                (port, ok) = QInputDialog.getItem(
                    self,
                    QCA.translate("AdminHomeHeating", "Seleccionar puerto"),
                    QCA.translate("AdminHomeHeating", "Seleccionar el puerto del display"),
                    analog_ports.keys(),
                    0,
                    False,
                )

                self.abort_operation_mode()
                self.start_operation_mode("add_display", {"position": None, "name": name, "port": port})
Пример #11
0
    def _specify_hdd(self):
        """
        Specify which HDD to unmount.

        Arguments:
        None

        Return:
        HDD text
        """
        text, result = QInputDialog().getText(
            self,
            'Specify hdd',
            'choose hdd to unmount,\n"all" will unmount all mounted hdd\'s',
            QLineEdit.Normal,
            'all'
            )
        if result:
            text = text.lower()
            if text.startswith('hdd_'):
                return text
            elif text.startswith('hdd '):
                return text
            elif text == 'all':
                return text
            else:
                tu.message('Input needs to be "all" or "hdd_{number}" or "hdd {number}')
                return None
        else:
            tu.message('Input needs to be "all" or "hdd_{number} or "hdd {number}"')
            return None
Пример #12
0
def getStringMsg( title, text, preset=None ):
    if preset is None:
        (ans, ok) = QInputDialog.getText(IMC.mainWindow, title, text)
    else:
        (ans, ok) = QInputDialog.getText(IMC.mainWindow, title, text,
                                         QLineEdit.Normal, preset)
    return (ans, ok)
Пример #13
0
 def goto(self, number=None):
     """ Ask event number in dialog and navigate and to event.
     """
     logging.debug(__name__ + ": goto")
     if self._dataAccessor.numberOfEvents():
         max = self._dataAccessor.numberOfEvents()
     else:
         max = sys.maxsize
     if number != None:
         ok = (number >= 1, number <= max)
     else:
         if hasattr(QInputDialog, "getInteger"):
             # Qt 4.3
             (number, ok) = QInputDialog.getInteger(
                 self.plugin().application().mainWindow(),
                 "Goto...", "Enter event number:",
                 self._dataAccessor.eventNumber(), 1, max)
         else:
             # Qt 4.5
             (number, ok) = QInputDialog.getInt(
                 self.plugin().application().mainWindow(),
                 "Goto...", "Enter event number:",
                 self._dataAccessor.eventNumber(), 1, max)
     if ok:
         self.cancel()
         currentEvent = self.dataAccessor().eventNumber()
         if currentEvent != number:
             self.navigate(number)
 def onCargajuegoClicked(self):
     """Nos permite Cargar un juego anteriormente guardado"""
     (nombre,ok) = QInputDialog.getText(self, self.tr("Sudoku"), self.tr("Nombre:"),QLineEdit.Normal, self.tr(""))
     if ok==True:
         while str(nombre)=="" and ok==True:
             self.MessageBox(None,"Ingrese Un Nombre..!","ERROR",self.MB_ICONERROR)
             (nombre,ok) = QInputDialog.getText(self, self.tr("Sudoku"), self.tr("Nombre:"),QLineEdit.Normal, self.tr(""))
         if ok==True:
             archivo=open("Partidas.txt","r")
             linea=archivo.readline()
             Existe=0
             while linea!="":
                 partida=linea.split(",")
                 nombreG=partida[0]
                 if str(nombre)==nombreG:
                     Existe=1
                     break
                 linea=archivo.readline()
             if Existe==1:
                 invalida=partida[3]
                 incorrecta=partida[4]
                 ayuda=partida[5]
                 self.n= Sudoku(5,invalida,incorrecta,ayuda,partida)
                 self.n.setVisible(True)
                 self.close()
             else:
                 self.MessageBox(None,"No Se Encontro El Archivo..!","ERROR",self.MB_ICONERROR)
             archivo.close()
Пример #15
0
 def insert_item(self):
     """Insert item"""
     index = self.currentIndex()
     if not index.isValid():
         row = self.model.rowCount()
     else:
         row = index.row()
     data = self.model.get_data()
     if isinstance(data, list):
         key = row
         data.insert(row, '')
     elif isinstance(data, dict):
         key, valid = QInputDialog.getText(
             self, translate("DictEditor", 'Insert'),
             translate("DictEditor", 'Key:'), QLineEdit.Normal)
         if valid and not key.isEmpty():
             key = try_to_eval(unicode(key))
         else:
             return
     else:
         return
     value, valid = QInputDialog.getText(self,
                                         translate("DictEditor", 'Insert'),
                                         translate("DictEditor", 'Value:'),
                                         QLineEdit.Normal)
     if valid and not value.isEmpty():
         self.new_value(key, try_to_eval(unicode(value)))
Пример #16
0
 def onActionguardarTriggered(self):
     """Guarda la partida actual
         Se pide el nombre con el que se desea guardar la partida y luego se procede a grabarla con encriptacion."""
     (nombre,ok) = QInputDialog.getText(self, self.tr("Sudoku"), self.tr("Nombre:"),QLineEdit.Normal, self.tr(""))
     if ok==True:
         while str(nombre)=="" and ok==True:
             self.MessageBox(None,"Ingrese Un Nombre..!","ERROR",self.MB_ICONERROR)
             (nombre,ok) = QInputDialog.getText(self, self.tr("Sudoku"), self.tr("Nombre:"),QLineEdit.Normal, self.tr(""))
         if ok==True:
             solucion=open("Resueltos.txt","a")
             solucion.write(str(nombre))
             solucion.write(",")
             for i in range(9):
                 for j in range(9):
                     solucion.write(str(self.resuelto[i][j]))
             solucion.write("\n")
             solucion.close()
             archivo=open("Partidas.txt","a")
             archivo.write(str(nombre))
             archivo.write(",")
             for i in range(9):
                 for j in range(9):
                     if self.numeros[i][j]==0:
                         archivo.write("j")
                     elif self.numeros[i][j]==1:
                         archivo.write("n")
                     elif self.numeros[i][j]==2:
                         archivo.write("l")
                     elif self.numeros[i][j]==3:
                         archivo.write("d")
                     elif self.numeros[i][j]==4:
                         archivo.write("y")
                     elif self.numeros[i][j]==5:
                         archivo.write("s")
                     elif self.numeros[i][j]==6:
                         archivo.write("t")
                     elif self.numeros[i][j]==7:
                         archivo.write("v")
                     elif self.numeros[i][j]==8:
                         archivo.write("a")
                     else:
                         archivo.write("e")
             archivo.write(",")
             archivo.write(self.cronometro)
             if self.invalida:
                 archivo.write(",1")
             else:
                 archivo.write(",0")
             if self.incorrecta:
                 archivo.write(",1")
             else:
                 archivo.write(",0")
             if self.ayuda:
                 archivo.write(",1")
             else:
                 archivo.write(",0")
             archivo.write("\n")
             archivo.close()
             self.MessageBox(None,"Partida Guardada..!","Sudoku",self.MB_ICONEXCLAMATION)
Пример #17
0
def edit_layer_point_size(layer):
    """ Interactively edit a layer's point size """
    dialog = QInputDialog()
    size, isok = dialog.getInt(None, 'Point Size', 'Point Size',
                               value=layer.style.markersize,
                               min=1, max=1000, step=1)
    if isok and size != layer.style.markersize:
        layer.style.markersize = size
Пример #18
0
 def on_importGoogleContactsButton_clicked(self):
     googleUsername, ok = QInputDialog.getText(self, 'Google Username', 'Enter your Google username/email', text=getConfig('googleUsername', ''))
     if not ok:
         return
     googlePassword, ok = QInputDialog.getText(self, 'Google Password', 'Enter your Google password', mode=QLineEdit.Password)
     if not ok:
         return
     setConfig('googleUsername', googleUsername)
     self.import_google_contacts_signal.emit(googleUsername, googlePassword)
Пример #19
0
    def add_var(self, source = 'input'):
        '''
        Adds a variable to the margins

        Parameters
        ----------
        source : str, default to 'free'
                 Can be 'free' (default), 'input' or 'output' according to the variable
        '''

#        TODO: fix this lists      = {'input': self.input_vars_list, 'output': self.output_vars_list, 'free': self.free_vars_list}

        lists      = {'input': self.input_vars_list}

        variables_list = lists[source]
        varnames = self.get_name_label_dict(variables_list) # {varname: varlabel}

        varlabel, ok = QInputDialog.getItem(self.parent(), "Ajouter une variable", "Nom de la variable",
                                           sorted(varnames.keys()))

        insertion = ok and (varlabel in sorted(varnames.keys()))
        if insertion:
            varname = varnames[varlabel]
            datatable_name = self.get_var_datatable(varname)
            target = None
            if source=='input' and self.input_margins_df:
                index = self.input_margins_df.index
                indices = [ (var, mod)  for (var, mod) in index if var==varname ]
                target_df = (self.input_margins_df['target'][indices]).reset_index()
                target = dict(zip(target_df['mod'] ,target_df['target']))
            else:
                if datatable_name =='output_table':
                    varcol = self.output_table.column_by_name.get(varname)
                elif datatable_name =='inputs':
                    varcol = self.inputs.column_by_name.get(varname)

                if varcol.__class__ not in MODCOLS:
                        val, ok = QInputDialog.getDouble(self.parent(), "Valeur de la  marge", unicode(varlabel) + "  (millions d'euros)")
                        if ok:
                            target = {str(varname): val*1e6}
                else:
                    if datatable_name =='output_table':
                        unique_values = unique(self.output_table.get_value(varname, self.entity))
                    elif datatable_name =='inputs':
                        unique_values = unique(self.inputs.get_value(varname, self.entity))
                    target = {}

                    for mod in unique_values:
                        val, ok = QInputDialog.getDouble(self.parent(), "Valeur de la  marge", unicode(varlabel) + u" pour la modalité " + str(mod) )
                        if ok:
                            target[mod] = val
                        else:
                            return

            if target:
                self.calibration.add_var2(varname, target = target, source=source)
                self.param_or_margins_changed()
Пример #20
0
    def __call__(self, val):
        dialog = QInputDialog(parent=self.parent)
#         dialog.setLabelText("")
        dialog.setLabelText("set label for minimum: " + str(self.minimum.energy))
        dialog.setInputMode(0)
        dialog.exec_()
        if dialog.result():
            label = dialog.textValue()
            self.parent._minima_labels[self.minimum] = label
Пример #21
0
    def add_var(self, source = 'input'):
        '''
        Adds a variable to the margins

        Parameters
        ----------
        source : str, default to 'free'
                 Can be 'free' (default), 'input' or 'output' according to the variable
        '''

#        TODO: fix this lists      = {'input': self.input_vars_list, 'output': self.output_vars_list, 'free': self.free_vars_list}

        lists      = {'input': self.input_vars_list}

        variables_list = lists[source]
        varnames = self.get_name_label_dict(variables_list) # {varname: varlabel}

        varlabel, ok = QInputDialog.getItem(self.parent(), "Ajouter une variable", "Nom de la variable",
                                           sorted(varnames.keys()))

        insertion = ok and (varlabel in sorted(varnames.keys()))
        if insertion:
            varname = varnames[varlabel]
            datatable_name = self.get_var_datatable(varname)
            target = None
            if source=='input' and self.input_margins_df:
                index = self.input_margins_df.index
                indices = [ (var, mod)  for (var, mod) in index if var==varname ]
                target_df = (self.input_margins_df['target'][indices]).reset_index()
                target = dict(zip(target_df['mod'] ,target_df['target']))
            else:
                if datatable_name =='output_table':
                    varcol = self.output_table.column_by_name.get(varname)
                elif datatable_name =='inputs':
                    varcol = self.inputs.column_by_name.get(varname)

                if varcol.__class__ not in MODCOLS:
                        val, ok = QInputDialog.getDouble(self.parent(), "Valeur de la  marge", unicode(varlabel) + "  (millions d'euros)")
                        if ok:
                            target = {str(varname): val*1e6}
                else:
                    if datatable_name =='output_table':
                        unique_values = unique(self.output_table.get_value(varname, self.entity))
                    elif datatable_name =='inputs':
                        unique_values = unique(self.inputs.get_value(varname, self.entity))
                    target = {}

                    for mod in unique_values:
                        val, ok = QInputDialog.getDouble(self.parent(), "Valeur de la  marge", unicode(varlabel) + u" pour la modalité " + str(mod) )
                        if ok:
                            target[mod] = val
                        else:
                            return

            if target:
                self.calibration.add_var2(varname, target = target, source=source)
                self.param_or_margins_changed()
Пример #22
0
 def writeConfiguration():
     key, ok = QInputDialog.getText(self, "Write Config Value", "Key:")
     if (not ok) or (not key):
         utils.informationBox("Cancelled.")
         return
     value, ok = QInputDialog.getText(self, "Write Config Value", "Value:")
     if (not ok) or (not value):
         utils.informationBox("Cancelled.")
         return
     self.config.writeConf(key, value)
Пример #23
0
 def zoomDialog(self):
     if hasattr(QInputDialog, "getInteger"):
         # Qt 4.3
         (zoom, ok) = QInputDialog.getInteger(self.tab(), "Zoom...", "Input zoom factor in percent:", self.zoom(), 0)
     else:
         # Qt 4.5
         (zoom, ok) = QInputDialog.getInt(self.tab(), "Zoom...", "Input zoom factor in percent:", self.zoom(), 0)
     if ok:
         self.setZoom(zoom)
         self._userZoomLevel = zoom
Пример #24
0
 def editContact(self, name='', conversationId=''):
     phone = conversationId.split('@')[0]
     if len(phone) == 0 or phone[0] != '+':
         phone = '+' + phone
     name, ok = QInputDialog.getText(self, 'Contact Name', 'Enter this contact\'s name', text=name)
     if not ok:
         return
     phone, ok = QInputDialog.getText(self, 'Contact Phone', 'Enter this contact\'s phone number\n(leading with a "+" and your country code)', text=phone)
     if not ok:
         return
     self.update_contact_signal.emit(name, phone)
Пример #25
0
def get_text(title='Enter a label'):
    """Prompt the user to enter text using QT

    :param title: Name of the prompt

    *Returns*
       The text the user typed, or None
    """
    dialog = QInputDialog()
    result, isok = dialog.getText(None, title, title)
    if isok:
        return str(result)
Пример #26
0
    def backup(self):
        try:
            selected_index = self.treeViewStorage.selectedIndexes()[0]
            selected_path = self.model_storage.filePath(selected_index).split(
                '/')[::-1]
            storage = ''
            for i, dir in enumerate(selected_path):
                if dir == "Backups":
                    storage = str(selected_path[i - 1])
            dialog = QInputDialog()
            dialog.setModal(True)
            key, ok = dialog.getText(self,
                                     "Key",
                                     "Enter key for <b>%s</b> storage" %
                                     storage,
                                     mode=QLineEdit.Password)
            if ok:
                #try:
                key = str(key)
                with open(self.current_dir + storage + sep + "init",
                          'rb') as f:
                    hash_from_storage = f.read(64)
                    cipter_text = f.read()
                    encryptor = AES.new(key + self.padding[len(key):])
                    plain = encryptor.decrypt(cipter_text)
                    if hash_from_storage == SHA256.new(plain).hexdigest():
                        self.password = key
                        self.encrypt_and_save_to(storage)
                    else:
                        QMessageBox.about(self, "Error", "Incorrect password!")
            #except UnicodeError:
            #    QMessageBox.about(self, "Unicode error", "Incorrect password!")

        except IndexError:
            if self.selected_storage:
                with open(
                        self.current_dir + self.selected_storage + sep +
                        "init", 'rb') as f:
                    hash_from_storage = f.read(64)
                    cipter_text = f.read()
                    encryptor = AES.new(self.password +
                                        self.padding[len(self.password):])
                    plain = encryptor.decrypt(cipter_text)
                    if hash_from_storage == SHA256.new(plain).hexdigest():
                        self.encrypt_and_save_to(self.selected_storage)
                    else:
                        QMessageBox.about(self, "Error",
                                          "Incorrect password! sel")
            else:
                QMessageBox.about(
                    self, "Error",
                    "Select the storage before creating backup!")
                self.tabWidgetRoot.setCurrentWidget(self.tab_storage)
Пример #27
0
	def _comenzar(self):
		ok = 0
		eleccion, ok1 = QInputDialog.getItem(self, "Algoritmos", "Seleccione un algoritmo", self.algoritmos.keys())
		if ok1:
			self.contenedor = self.algoritmos[str(eleccion)]()
			self.cant, ok = QInputDialog.getInt(self, "Duracion", "Indique la duracion de la simulacion", min=0, max=60)
		if ok and ok1:
			self.setWindowTitle(self.windowTitle() + " --" +str(eleccion))
			self.temporizador.start(1000)
			self.iniciar.setEnabled(False)
			self.bloquear.setEnabled(True)
		self._inicializarDatos()
Пример #28
0
    def __call__(self, val):
        dialog = QInputDialog(parent=self.parent)
#         dialog.setLabelText("")
        dialog.setLabelText("set label for minimum: " + str(self.minimum.energy))
        dialog.setInputMode(0)
        dialog.exec_()
        if dialog.result():
            label = dialog.textValue()
            self.parent._minima_labels[self.minimum] = label
Пример #29
0
 def expandToDepthDialog(self):
     """ Show dialog and expand center view to depth.
     """
     if hasattr(QInputDialog, "getInteger"):
         # Qt 4.3
         (depth, ok) = QInputDialog.getInteger(self.tab(), "Expand to depth...", "Input depth:", self._treeDepth, 0)
     else:
         # Qt 4.5
         (depth, ok) = QInputDialog.getInt(self.tab(), "Expand to depth...", "Input depth:", self._treeDepth, 0)
     if ok:
         self._treeDepth=depth
         if self.tab().treeView().selection():
             self.onTreeViewSelected(self.tab().treeView().selection())
Пример #30
0
def edit_layer_symbol(layer):
    """ Interactively edit a layer's symbol """
    dialog = QInputDialog()
    options = ['o', '^', '*', 's']
    try:
        initial = options.index(layer.style.marker)
    except IndexError:
        initial = 0
    symb, isok = dialog.getItem(None, 'Pick a Symbol',
                                'Pick a Symbol',
                                options, current=initial)
    if isok and symb != layer.style.marker:
        layer.style.marker = symb
Пример #31
0
 def expandToDepthDialog(self):
     """ Show dialog and call expandToDepth() function of tree view.
     """
     if hasattr(QInputDialog, "getInteger"):
         # Qt 4.3
         (depth, ok) = QInputDialog.getInteger(self, "Expand to depth...", "Input depth:", self._treeDepth, 0)
     else:
         # Qt 4.5
         (depth, ok) = QInputDialog.getInt(self, "Expand to depth...", "Input depth:", self._treeDepth, 0)
     if ok:
         self._treeDepth=depth
         self.collapseAll(False)
         if self._treeDepth>0:
             self.expandToDepth(self._treeDepth-1)
Пример #32
0
    def continue_dialog(self, text1, text2):
        """
        Check if the user wants to run the continue mode.

        Arguments:
        text1 - Dialog window name.
        text2 - Text of the dialog.

        Return:
        True, if the input is YES!
        """
        dialog = QInputDialog(self)
        result = dialog.getText(self, text1, text2)
        return bool(result[0] == 'YES!')
Пример #33
0
 def on_gerar_arestas_button_clicked(self):
     self.limparInferencias()
     self.grafo.limpar()
     n_linhas = self.tabela_adjacencia.rowCount()
     n_colunas = self.tabela_adjacencia.columnCount()
     for x in xrange(n_linhas):
         for y in xrange(x,n_colunas):
             item = self.tabela_adjacencia.cellWidget(x, y)
             if item.currentText() == '1':
                 v1 = str(self.tabela_adjacencia.horizontalHeaderItem(x).text())
                 v2 = str(self.tabela_adjacencia.verticalHeaderItem(y).text())
                 valor = None
                 if self.valorar_aresta.isChecked():
                     ok = False
                     while not ok:
                         valor,ok = QInputDialog().getText(self, 'Dados para a aresta {0}-{1} (separados por ",")'.format(v1,v2), 
                                                        'Dados:', mode=QLineEdit.Normal, 
                                                        text=QString())
                         valor = str(valor)
                         if not ok:
                             sair = QMessageBox.question(self, 'Cancelar?', u'deseja cancelar a criação do grafo?',
                                                         buttons=QMessageBox.Yes | QMessageBox.No, defaultButton=QMessageBox.NoButton)
                             
                             if sair == QMessageBox.Yes:
                                 self.grafo.limpar()
                                 return
                         elif valor == '':
                             atribuir_zero = QMessageBox.question(self, 'Valor em branco!', u'Atribuit valor "0" à aresta?', 
                                                                  buttons=QMessageBox.Yes | QMessageBox.No, defaultButton=QMessageBox.NoButton)
                             if atribuir_zero:
                                 valor = '0'
                             else:
                                 valor = None
                         valor = valor.split(',')
                         valor = {string.split(':')[0]:string.split(':')[1] for string in valor}
                         for dado in valor:
                             if valor[dado].isdigit():
                                 valor[dado] = int(valor[dado])
                             else:
                                 try:
                                     valor[dado] = float(valor[dado])
                                 except ValueError:
                                     pass
                 
                 self.grafo.adicionarAresta(v1, v2, valor)
     self.eh_conexo.setChecked(self.grafo.ehConexo())
     self.eh_arvore.setChecked(self.grafo.ehArvore())
     self.eh_regular.setChecked(self.grafo.ehRegular())
     self.eh_completo.setChecked(self.grafo.ehCompleto())
Пример #34
0
 def zoomDialog(self):
     if hasattr(QInputDialog, "getInteger"):
         # Qt 4.3
         (zoom,
          ok) = QInputDialog.getInteger(self.tab(), "Zoom...",
                                        "Input zoom factor in percent:",
                                        self.zoom(), 0)
     else:
         # Qt 4.5
         (zoom, ok) = QInputDialog.getInt(self.tab(), "Zoom...",
                                          "Input zoom factor in percent:",
                                          self.zoom(), 0)
     if ok:
         self.setZoom(zoom)
         self._userZoomLevel = zoom
Пример #35
0
def get_text(title="Enter a label"):
    """Prompt the user to enter text using QT

    Parameters
    ----------
    title : Name of the prompt

    Returns
    -------
    The text the user typed, or None
    """
    dialog = QInputDialog()
    result, isok = dialog.getText(None, title, title)
    if isok:
        return str(result)
Пример #36
0
 def __call__(self):
     password, ok = QInputDialog.getText(None,
         '%s request' % self.value.label,
         'Please enter %s for %s' % (self.value.label,
                                     self.backend_name),
                                         QLineEdit.Password)
     return password
Пример #37
0
 def __call__(self):
     password, ok = QInputDialog.getText(None,
         '%s request' % self.value.label,
         'Please enter %s for %s' % (self.value.label,
                                     self.backend_name),
                                         QLineEdit.Password)
     return password
Пример #38
0
 def rename_file(self, fname):
     """Rename file"""
     path, valid = QInputDialog.getText(self, _('Rename'),
                                        _('New name:'), QLineEdit.Normal,
                                        osp.basename(fname))
     if valid:
         path = osp.join(osp.dirname(fname), unicode(path))
         if path == fname:
             return
         if osp.exists(path):
             if QMessageBox.warning(
                     self, _("Rename"),
                     _("Do you really want to rename <b>%s</b> and "
                       "overwrite the existing file <b>%s</b>?") %
                 (osp.basename(fname), osp.basename(path)),
                     QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                 return
         try:
             misc.rename_file(fname, path)
             self.parent_widget.emit( \
                  SIGNAL("renamed(QString,QString)"), fname, path)
             return path
         except EnvironmentError, error:
             QMessageBox.critical(
                 self, _("Rename"),
                 _("<b>Unable to rename file <i>%s</i></b>"
                   "<br><br>Error message:<br>%s") %
                 (osp.basename(fname), unicode(error)))
Пример #39
0
 def on_importGoogleContactsButton_clicked(self):
     googleUsername, ok = QInputDialog.getText(
         self,
         'Google Username',
         'Enter your Google username/email',
         text=getConfig('googleUsername', ''))
     if not ok:
         return
     googlePassword, ok = QInputDialog.getText(self,
                                               'Google Password',
                                               'Enter your Google password',
                                               mode=QLineEdit.Password)
     if not ok:
         return
     setConfig('googleUsername', googleUsername)
     self.import_google_contacts_signal.emit(googleUsername, googlePassword)
Пример #40
0
    def _add_new_file(self):
        item = self.currentItem()
        if item.parent() is None:
            pathForFile = item.path
        else:
            pathForFile = os.path.join(item.path, item.text(0))
        result = QInputDialog.getText(self, self.tr("New File"),
                                      self.tr("Enter the File Name:"))
        fileName = result[0]

        if result[1] and fileName.strip() != '':
            try:
                fileName = os.path.join(pathForFile, fileName)
                fileName = file_manager.store_file_content(fileName,
                                                           '',
                                                           newFile=True)
                name = file_manager.get_basename(fileName)
                subitem = ProjectItem(item, name, pathForFile)
                subitem.setToolTip(0, name)
                subitem.setIcon(0, self._get_file_icon(name))
                mainContainer = main_container.MainContainer()
                mainContainer.open_file(fileName)
            except file_manager.NinjaFileExistsException as ex:
                QMessageBox.information(
                    self, self.tr("File Already Exists"),
                    self.tr("Invalid Path: the file '%s' already exists." %
                            ex.filename))
Пример #41
0
 def _copy_file(self):
     #get the selected QTreeWidgetItem
     item = self.currentItem()
     if item.parent() is None:
         pathForFile = item.path
     else:
         pathForFile = os.path.join(item.path, item.text(0))
     pathProjects = [p.path for p in self.get_open_projects()]
     addToProject = ui_tools.AddToProject(pathProjects, self)
     addToProject.setWindowTitle(self.tr("Copy File to"))
     addToProject.exec_()
     if not addToProject.pathSelected:
         return
     name = QInputDialog.getText(self, self.tr("Copy File"),
         self.tr("File Name:"), text=item.text(0))[0]
     if not name:
         QMessageBox.information(self, self.tr("Invalid Name"),
             self.tr("The file name is empty, please enter a name"))
         return
     path = file_manager.create_path(addToProject.pathSelected, name)
     try:
         content = file_manager.read_file_content(pathForFile)
         path = file_manager.store_file_content(path, content, newFile=True)
         self.add_existing_file(path)
     except file_manager.NinjaFileExistsException as ex:
             QMessageBox.information(self, self.tr("File Already Exists"),
                 self.tr("Invalid Path: the file '%s' already exists." %
                     ex.filename))
Пример #42
0
    def sizeHint(self):
        size = QInputDialog.sizeHint(self)

        if size.width() < 400:
            size.setWidth(400)

        return size
Пример #43
0
def insert_debugging_prints(editorWidget):
    cursor = editorWidget.textCursor()
    if cursor.hasSelection():
        result = str(QInputDialog.getText(editorWidget,
            editorWidget.tr("Print Text"),
            editorWidget.tr("Insert a Text to use in the Print or "
                            "leave empty to just print numbers:"))[0])
        print_text = ""
        if result:
            print_text = "%s: " % result
        #begin Undo feature
        cursor.beginEditBlock()
        start = editorWidget.document().findBlock(
            cursor.selectionStart()).firstLineNumber()
        end = editorWidget.document().findBlock(
            cursor.selectionEnd()).firstLineNumber()
        lines = end - start
        for i in range(lines):
            position = editorWidget.document().findBlockByLineNumber(
                start + (i * 2)).position()
            cursor.setPosition(position)
            indentation = get_indentation(cursor.block().text())
            cursor.movePosition(QTextCursor.EndOfLine)
            cursor.insertText("\n%sprint('%s%i')" % (
                indentation, print_text, i))
        #end Undo feature
        cursor.endEditBlock()
Пример #44
0
 def createView(self):
     name, ok = QInputDialog.getText(None, "View name", "View name")
     if ok:
         try:
             self.db.connector.createSpatialView(name, self._getSqlQuery())
         except BaseError as e:
             DlgDbError.showError(e, self)
Пример #45
0
def newfoldername(basetext, basefolder, formtype, alreadyexists=False):
    message = "Please enter a new folder name for the {}".format(formtype)
    if alreadyexists:
        logger.log("Folder {} already exists.")
        message += "<br> {} folder already exists please select a new one.".format(
            formtype)

    name, ok = QInputDialog.getText(None,
                                    "New {} folder name".format(formtype),
                                    message)
    if not ok:
        raise ValueError

    if not name:
        return "{}_{}".format(basetext, datetime.today().strftime('%d%m%y%f'))
    else:
        name = name.replace(" ", "_")

    if os.path.exists(os.path.join(basefolder, name)):
        return newfoldername(basetext,
                             basefolder,
                             formtype,
                             alreadyexists=True)

    return name
Пример #46
0
 def _copy_file(self):
     #get the selected QTreeWidgetItem
     path = self.model().filePath(self.currentIndex())
     name = file_manager.get_basename(path)
     global projectsColumn
     pathProjects = [p.path for p in projectsColumn.projects]
     addToProject = add_to_project.AddToProject(pathProjects, self)
     addToProject.setWindowTitle(self.tr("Copy File to"))
     addToProject.exec_()
     if not addToProject.pathSelected:
         return
     name = QInputDialog.getText(self, self.tr("Copy File"),
         self.tr("File Name:"), text=name)[0]
     if not name:
         QMessageBox.information(self, self.tr("Invalid Name"),
             self.tr("The file name is empty, please enter a name"))
         return
     path = file_manager.create_path(addToProject.pathSelected, name)
     try:
         content = file_manager.read_file_content(path)
         path = file_manager.store_file_content(path, content, newFile=True)
     except file_manager.NinjaFileExistsException as ex:
             QMessageBox.information(self, self.tr("File Already Exists"),
                 (self.tr("Invalid Path: the file '%s' already exists.") %
                     ex.filename))
Пример #47
0
 def showClusterTable(self):
     if not self.view.sampleTableView.selectedIndexes(
     ):  #not self.acTree.selectedIndexes():
         s, b = QInputDialog.getItem(
             self.view, "Select one sample", "Select one sample :",
             [spl.shortName() for spl in self.model])
         if not b:
             return
         sample = self.model.sample(str(s), fullNameEntry=False)
     else:
         idx = self.view.sampleTableView.selectedIndexes()[0]
         sample = self.model.sample(idx.data().toString(),
                                    fullNameEntry=False)
     if sample is None:
         print("sample not found...")
         return
     if not sample.mappedPeaks:
         self.view.showErrorMessage(
             "No peaks found",
             "This sample does not have peaks, please do peak picking before"
         )
     view = QTableView()
     view.setSortingEnabled(True)
     view.horizontalHeader().setStretchLastSection(True)
     view.setModel(
         MSDialogController.getSampleModel(sample, flags='cluster'))
     self.view.addMdiSubWindow(view,
                               "ClusterList of%s" % str(sample.shortName()))
Пример #48
0
 def _copy_file(self):
     #get the selected QTreeWidgetItem
     item = self.currentItem()
     if item.parent() is None:
         pathForFile = item.path
     else:
         pathForFile = os.path.join(item.path, item.text(0))
     pathProjects = [p.path for p in self.get_open_projects()]
     addToProject = ui_tools.AddToProject(pathProjects, self)
     addToProject.setWindowTitle(self.tr("Copy File to"))
     addToProject.exec_()
     if not addToProject.pathSelected:
         return
     name = QInputDialog.getText(self,
                                 self.tr("Copy File"),
                                 self.tr("File Name:"),
                                 text=item.text(0))[0]
     if not name:
         QMessageBox.information(
             self, self.tr("Invalid Name"),
             self.tr("The file name is empty, please enter a name"))
         return
     path = file_manager.create_path(addToProject.pathSelected, name)
     try:
         content = file_manager.read_file_content(pathForFile)
         path = file_manager.store_file_content(path, content, newFile=True)
         self.add_existing_file(path)
     except file_manager.NinjaFileExistsException as ex:
         QMessageBox.information(
             self, self.tr("File Already Exists"),
             self.tr("Invalid Path: the file '%s' already exists." %
                     ex.filename))
Пример #49
0
    def _rename_file(self):
        item = self.currentItem()
        if item.parent() is None:
            pathForFile = item.path
        else:
            pathForFile = os.path.join(item.path, item.text(0))
        result = QInputDialog.getText(self,
                                      self.tr("Rename File"),
                                      self.tr("Enter New File Name:"),
                                      text=item.text(0))
        fileName = result[0]

        if result[1] and fileName.strip() != '':
            fileName = os.path.join(file_manager.get_folder(pathForFile),
                                    fileName)
            if pathForFile == fileName:
                return
            try:
                fileName = file_manager.rename_file(pathForFile, fileName)
                name = file_manager.get_basename(fileName)
                mainContainer = main_container.MainContainer()
                if mainContainer.is_open(pathForFile):
                    mainContainer.change_open_tab_name(pathForFile, fileName)
                subitem = ProjectItem(item.parent(), name,
                                      file_manager.get_folder(fileName))
                subitem.setToolTip(0, name)
                subitem.setIcon(0, self._get_file_icon(name))
                index = item.parent().indexOfChild(item)
                subitem.parent().takeChild(index)
            except file_manager.NinjaFileExistsException as ex:
                QMessageBox.information(
                    self, self.tr("File Already Exists"),
                    self.tr("Invalid Path: the file '%s' already exists." %
                            ex.filename))
Пример #50
0
    def _add_new_file(self):
        item = self.currentItem()
        if item.parent() is None:
            pathForFile = item.path
        else:
            pathForFile = os.path.join(item.path, item.text(0))
        result = QInputDialog.getText(self, self.tr("New File"),
            self.tr("Enter the File Name:"))
        fileName = result[0]

        if result[1] and fileName.strip() != '':
            try:
                fileName = os.path.join(pathForFile, fileName)
                fileName = file_manager.store_file_content(
                    fileName, '', newFile=True)
                name = file_manager.get_basename(fileName)
                subitem = ProjectItem(item, name, pathForFile)
                subitem.setToolTip(0, name)
                subitem.setIcon(0, self._get_file_icon(name))
                mainContainer = main_container.MainContainer()
                mainContainer.open_file(fileName)
            except file_manager.NinjaFileExistsException as ex:
                QMessageBox.information(self, self.tr("File Already Exists"),
                    self.tr("Invalid Path: the file '%s' already exists." %
                        ex.filename))
Пример #51
0
 def showPeakTable(self):
     """
     TODO: write little function to check if sample is None or good
     or write exception with good code
     
     """
     if not self.view.sampleTableView.selectedIndexes(
     ):  #not self.acTree.selectedIndexes():
         s, b = QInputDialog.getItem(
             self.view, "Select one sample", "Select one sample :",
             [spl.shortName() for spl in self.model])
         if not b:
             return
         sample = self.model.sample(str(s), fullNameEntry=False)
     else:
         idx = self.view.sampleTableView.selectedIndexes()[0]
         sample = self.model.sample(idx.data().toString(),
                                    fullNameEntry=False)
     if sample is None:
         print("sample not found...")
         return
     if not sample.rawPeaks:
         self.view.showErrorMessage(
             "No peaks found",
             "This sample does not have peaks, please do peak picking before"
         )
     view = QTableView()
     view.horizontalHeader().setStretchLastSection(True)
     view.setSortingEnabled(True)
     model = MSDialogController.getSampleModel(sample, flags='peak')
     view.setModel(model)
     self.view.addMdiSubWindow(
         view, " ".join(["PeakList of",
                         str(sample.shortName())]))
Пример #52
0
    def _rename_file(self):
        item = self.currentItem()
        if item.parent() is None:
            pathForFile = item.path
        else:
            pathForFile = os.path.join(item.path, item.text(0))
        result = QInputDialog.getText(self, self.tr("Rename File"),
            self.tr("Enter New File Name:"), text=item.text(0))
        fileName = result[0]

        if result[1] and fileName.strip() != '':
            fileName = os.path.join(
                file_manager.get_folder(pathForFile), fileName)
            if pathForFile == fileName:
                return
            try:
                fileName = file_manager.rename_file(pathForFile, fileName)
                name = file_manager.get_basename(fileName)
                mainContainer = main_container.MainContainer()
                if mainContainer.is_open(pathForFile):
                    mainContainer.change_open_tab_name(pathForFile, fileName)
                subitem = ProjectItem(item.parent(), name,
                    file_manager.get_folder(fileName))
                subitem.setToolTip(0, name)
                subitem.setIcon(0, self._get_file_icon(name))
                index = item.parent().indexOfChild(item)
                subitem.parent().takeChild(index)
            except file_manager.NinjaFileExistsException as ex:
                QMessageBox.information(self, self.tr("File Already Exists"),
                    self.tr("Invalid Path: the file '%s' already exists." %
                        ex.filename))
Пример #53
0
    def newExperiment(self):
        if self.dirty:
            success = self.showDirtySaveBox()
            if not success:
                return False

        basePath = str(QFileDialog.getExistingDirectory(self, "New experiment storage path:", EXPERIMENT_DIR))
        if basePath == "":
            return False

        basePath = basePath.replace(os.getcwd() + "/", "")

        name, accepted = QInputDialog.getText( self, "Experiment Name", "New experiment name:")
        if not accepted:
            return False

        name = str(name)

        self.resetUI()
        self.enableUI()

        self.storage = FileStorage(name, basePath)
        self.experiment = self.storage.base

        self.ui.nameText.setText(name)
        return True
Пример #54
0
 def useLayerExtent(self):
     CANVAS_KEY = 'Use canvas extent'
     extentsDict = {}
     extentsDict[CANVAS_KEY] = {
         "extent": iface.mapCanvas().extent(),
         "authid":
         iface.mapCanvas().mapRenderer().destinationCrs().authid()
     }
     extents = [CANVAS_KEY]
     layers = dataobjects.getAllLayers()
     for layer in layers:
         authid = layer.crs().authid()
         if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF) \
                 and authid is not None:
             layerName = u'{} [{}]'.format(layer.name(), authid)
         else:
             layerName = layer.name()
         extents.append(layerName)
         extentsDict[layerName] = {
             "extent": layer.extent(),
             "authid": authid
         }
     (item, ok) = QInputDialog.getItem(self, self.tr('Select extent'),
                                       self.tr('Use extent from'), extents,
                                       False)
     if ok:
         self.setValueFromRect(extentsDict[item]["extent"])
         if extentsDict[item]["authid"] != iface.mapCanvas().mapRenderer(
         ).destinationCrs().authid():
             iface.messageBar().pushMessage(
                 self.tr("Warning"),
                 self.
                 tr("The projection of the chosen layer is not the same as canvas projection! The selected extent might not be what was intended."
                    ), QgsMessageBar.WARNING, 8)
Пример #55
0
        def edit_parameters(self):
            allaxes = self.canvas.figure.get_axes()
            if len(allaxes) == 1:
                axes = allaxes[0]
            else:
                titles = []
                for axes in allaxes:
                    title = axes.get_title()
                    ylabel = axes.get_ylabel()
                    label = axes.get_label()
                    if title:
                        fmt = "%(title)s"
                        if ylabel:
                            fmt += ": %(ylabel)s"
                        fmt += " (%(axes_repr)s)"
                    elif ylabel:
                        fmt = "%(axes_repr)s (%(ylabel)s)"
                    elif label:
                        fmt = "%(axes_repr)s (%(label)s)"
                    else:
                        fmt = "%(axes_repr)s"
                    titles.append(fmt % dict(title=title,
                                             ylabel=ylabel,
                                             label=label,
                                             axes_repr=repr(axes)))
                item, ok = QInputDialog.getItem(self.parent, 'Customize',
                                                'Select axes:', titles, 0,
                                                False)
                if ok:
                    axes = allaxes[titles.index(six.text_type(item))]
                else:
                    return

            figureoptions.figure_edit(axes, self)
Пример #56
0
    def save_sensor(self):
        """
            save single sensor,
            create a new one or overwrite existing one
        """
        if self.overFilter.isChecked():
            self.oat.save_to_sqlite(config.db_path, overwrite=True)
            return True
        else:
            new_sensor = copy.deepcopy(self.oat)

            new_name, ok = QInputDialog.getText(
                self, self.tr('Sensor name'),
                self.tr('Enter a new sensor name:'))

            new_sensor.name = new_name
            if not ok:
                return False
            try:
                new_sensor.save_to_sqlite(config.db_path)
            except IOError as _:
                QMessageBox.about(self, "Error",
                                  "Sensor name already exists...")
                return False
            return True
Пример #57
0
    def pulsa_boton_crear_archivo_nuevo(self):
        text, ok = QInputDialog.getText(self, 'Crear un archivo nuevo',
                                        'Nombre del archivo:',
                                        QLineEdit.Normal, "nuevo")

        if ok and text:
            self.editor.crear_y_seleccionar_archivo(text)
Пример #58
0
 def createView(self):
     name, ok = QInputDialog.getText(None, "View name", "View name")
     if ok:
         try:
             self.db.connector.createSpatialView(name, self._getSqlQuery())
         except BaseError as e:
             DlgDbError.showError(e, self)
Пример #59
0
def insert_debugging_prints(editorWidget):
    cursor = editorWidget.textCursor()
    if cursor.hasSelection():
        result = str(QInputDialog.getText(editorWidget,
            editorWidget.tr("Print Text"),
            editorWidget.tr("Insert a Text to use in the Print or "
                            "leave empty to just print numbers:"))[0])
        print_text = ""
        if result:
            print_text = "%s: " % result
        #begin Undo feature
        cursor.beginEditBlock()
        start = editorWidget.document().findBlock(
            cursor.selectionStart()).firstLineNumber()
        end = editorWidget.document().findBlock(
            cursor.selectionEnd()).firstLineNumber()
        lines = end - start
        for i in range(lines):
            position = editorWidget.document().findBlockByLineNumber(
                start + (i * 2)).position()
            cursor.setPosition(position)
            indentation = get_indentation(cursor.block().text())
            cursor.movePosition(QTextCursor.EndOfLine)
            cursor.insertText("\n%sprint('%s%i')" % (
                indentation, print_text, i))
        #end Undo feature
        cursor.endEditBlock()