Exemplo n.º 1
0
class Buscador(QWidget):
    status_signal = Signal(str)

    def __init__(self):
        self.db = ClientesDB()
        QWidget.__init__(self)
        Font = QFont()
        Font.setBold(True)  # Labels em Negrito

        # Entry:
        self.entry_nome = QLineEdit()
        self.entry_nome.setText("Nome para Busca")

        # Botões
        self.button_busca = QPushButton("&Busca")
        self.button_busca.clicked.connect(self.buscar)
        self.button_busca.setShortcut("Ctrl+B")
        self.button_limpar = QPushButton("Limpar")
        self.button_limpar.clicked.connect(self.limpar)
        self.button_limpar.setShortcut("ESC")

        # Tabela
        self.clientes = 0
        self.tabela_clientes = QTableWidget()
        self.tabela_clientes.setColumnCount(4)
        self.tabela_clientes.setHorizontalHeaderLabels([
            "Nome",
            "Número",
            "CPF",
            "Endereço",
        ])
        self.tabela_clientes.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.tabela_clientes.horizontalHeader().setStretchLastSection(True)
        self.tabela_clientes.resizeColumnsToContents()
        self.tabela_clientes.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tabela_clientes.itemDoubleClicked.connect(self.info_cliente)

        #Leiaute:
        self.layout = QVBoxLayout()
        self.layout_busca = QHBoxLayout()
        self.layout_busca.addWidget(self.entry_nome)
        self.layout_busca.addWidget(self.button_busca)
        self.layout.addLayout(self.layout_busca)
        self.layout.addWidget(self.tabela_clientes)
        self.setLayout(self.layout)

    @Slot()
    def buscar(self):
        nome_buscado = self.entry_nome.text()
        data = self.db.busca(nome_buscado)
        self.limpar()
        self.status_signal.emit("Feito")
        for cliente in data:
            nome = QTableWidgetItem(cliente['nome'])
            numero = QTableWidgetItem(cliente['numero'])
            cpf = QTableWidgetItem(cliente['cpf'])
            endereco = QTableWidgetItem(cliente['endereco'])
            nome.setTextAlignment(Qt.AlignCenter)
            numero.setTextAlignment(Qt.AlignCenter)
            cpf.setTextAlignment(Qt.AlignCenter)
            endereco.setTextAlignment(Qt.AlignCenter)
            self.tabela_clientes.insertRow(self.clientes)
            self.tabela_clientes.setItem(self.clientes, 0, nome)
            self.tabela_clientes.setItem(self.clientes, 1, numero)
            self.tabela_clientes.setItem(self.clientes, 2, cpf)
            self.tabela_clientes.setItem(self.clientes, 3, endereco)
            self.clientes += 1

    @Slot()
    def limpar(self):
        self.tabela_clientes.clearContents()
        self.tabela_clientes.setRowCount(0)
        self.clientes = 0

    @Slot()
    def info_cliente(self):
        pass
Exemplo n.º 2
0
class Snippets(QDialog):
    def __init__(self, context, parent=None):
        super(Snippets, self).__init__(parent)
        # Create widgets
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.title = QLabel(self.tr("Snippet Editor"))
        self.saveButton = QPushButton(self.tr("&Save"))
        self.saveButton.setShortcut(QKeySequence(self.tr("Ctrl+S")))
        self.runButton = QPushButton(self.tr("&Run"))
        self.runButton.setShortcut(QKeySequence(self.tr("Ctrl+R")))
        self.closeButton = QPushButton(self.tr("Close"))
        self.clearHotkeyButton = QPushButton(self.tr("Clear Hotkey"))
        self.setWindowTitle(self.title.text())
        #self.newFolderButton = QPushButton("New Folder")
        self.browseButton = QPushButton("Browse Snippets")
        self.browseButton.setIcon(QIcon.fromTheme("edit-undo"))
        self.deleteSnippetButton = QPushButton("Delete")
        self.newSnippetButton = QPushButton("New Snippet")
        indentation = Settings().get_string("snippets.indentation")
        if Settings().get_bool("snippets.syntaxHighlight"):
            self.edit = QCodeEditor(SyntaxHighlighter=Pylighter,
                                    delimeter=indentation)
        else:
            self.edit = QCodeEditor(SyntaxHighlighter=None,
                                    delimeter=indentation)
        self.edit.setPlaceholderText("python code")
        self.resetting = False
        self.columns = 3
        self.context = context

        self.keySequenceEdit = QKeySequenceEdit(self)
        self.currentHotkey = QKeySequence()
        self.currentHotkeyLabel = QLabel("")
        self.currentFileLabel = QLabel()
        self.currentFile = ""
        self.snippetDescription = QLineEdit()
        self.snippetDescription.setPlaceholderText("optional description")

        #Set Editbox Size
        font = getMonospaceFont(self)
        self.edit.setFont(font)
        font = QFontMetrics(font)
        self.edit.setTabStopDistance(
            4 * font.horizontalAdvance(' '))  #TODO, replace with settings API

        #Files
        self.files = QFileSystemModel()
        self.files.setRootPath(snippetPath)
        self.files.setNameFilters(["*.py"])

        #Tree
        self.tree = QTreeView()
        self.tree.setModel(self.files)
        self.tree.setSortingEnabled(True)
        self.tree.hideColumn(2)
        self.tree.sortByColumn(0, Qt.AscendingOrder)
        self.tree.setRootIndex(self.files.index(snippetPath))
        for x in range(self.columns):
            #self.tree.resizeColumnToContents(x)
            self.tree.header().setSectionResizeMode(
                x, QHeaderView.ResizeToContents)
        treeLayout = QVBoxLayout()
        treeLayout.addWidget(self.tree)
        treeButtons = QHBoxLayout()
        #treeButtons.addWidget(self.newFolderButton)
        treeButtons.addWidget(self.browseButton)
        treeButtons.addWidget(self.newSnippetButton)
        treeButtons.addWidget(self.deleteSnippetButton)
        treeLayout.addLayout(treeButtons)
        treeWidget = QWidget()
        treeWidget.setLayout(treeLayout)

        # Create layout and add widgets
        buttons = QHBoxLayout()
        buttons.addWidget(self.clearHotkeyButton)
        buttons.addWidget(self.keySequenceEdit)
        buttons.addWidget(self.currentHotkeyLabel)
        buttons.addWidget(self.closeButton)
        buttons.addWidget(self.runButton)
        buttons.addWidget(self.saveButton)

        description = QHBoxLayout()
        description.addWidget(QLabel(self.tr("Description: ")))
        description.addWidget(self.snippetDescription)

        vlayoutWidget = QWidget()
        vlayout = QVBoxLayout()
        vlayout.addLayout(description)
        vlayout.addWidget(self.edit)
        vlayout.addLayout(buttons)
        vlayoutWidget.setLayout(vlayout)

        hsplitter = QSplitter()
        hsplitter.addWidget(treeWidget)
        hsplitter.addWidget(vlayoutWidget)

        hlayout = QHBoxLayout()
        hlayout.addWidget(hsplitter)

        self.showNormal()  #Fixes bug that maximized windows are "stuck"
        #Because you can't trust QT to do the right thing here
        if (sys.platform == "darwin"):
            self.settings = QSettings("Vector35", "Snippet Editor")
        else:
            self.settings = QSettings("Vector 35", "Snippet Editor")
        if self.settings.contains("ui/snippeteditor/geometry"):
            self.restoreGeometry(
                self.settings.value("ui/snippeteditor/geometry"))
        else:
            self.edit.setMinimumWidth(80 * font.averageCharWidth())
            self.edit.setMinimumHeight(30 * font.lineSpacing())

        # Set dialog layout
        self.setLayout(hlayout)

        # Add signals
        self.saveButton.clicked.connect(self.save)
        self.closeButton.clicked.connect(self.close)
        self.runButton.clicked.connect(self.run)
        self.clearHotkeyButton.clicked.connect(self.clearHotkey)
        self.tree.selectionModel().selectionChanged.connect(self.selectFile)
        self.newSnippetButton.clicked.connect(self.newFileDialog)
        self.deleteSnippetButton.clicked.connect(self.deleteSnippet)
        #self.newFolderButton.clicked.connect(self.newFolder)
        self.browseButton.clicked.connect(self.browseSnippets)

        if self.settings.contains("ui/snippeteditor/selected"):
            selectedName = self.settings.value("ui/snippeteditor/selected")
            self.tree.selectionModel().select(
                self.files.index(selectedName),
                QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows)
            if self.tree.selectionModel().hasSelection():
                self.selectFile(self.tree.selectionModel().selection(), None)
                self.edit.setFocus()
                cursor = self.edit.textCursor()
                cursor.setPosition(self.edit.document().characterCount() - 1)
                self.edit.setTextCursor(cursor)
            else:
                self.readOnly(True)
        else:
            self.readOnly(True)

    @staticmethod
    def registerAllSnippets():
        for action in list(
                filter(lambda x: x.startswith("Snippets\\"),
                       UIAction.getAllRegisteredActions())):
            if action == "Snippets\\Snippet Editor...":
                continue
            UIActionHandler.globalActions().unbindAction(action)
            Menu.mainMenu("Tools").removeAction(action)
            UIAction.unregisterAction(action)

        for snippet in includeWalk(snippetPath, ".py"):
            snippetKeys = None
            (snippetDescription, snippetKeys,
             snippetCode) = loadSnippetFromFile(snippet)
            actionText = actionFromSnippet(snippet, snippetDescription)
            if snippetCode:
                if snippetKeys == None:
                    UIAction.registerAction(actionText)
                else:
                    UIAction.registerAction(actionText, snippetKeys)
                UIActionHandler.globalActions().bindAction(
                    actionText,
                    UIAction(makeSnippetFunction(snippetCode, actionText)))
                Menu.mainMenu("Tools").addAction(actionText, "Snippets")

    def clearSelection(self):
        self.keySequenceEdit.clear()
        self.currentHotkey = QKeySequence()
        self.currentHotkeyLabel.setText("")
        self.currentFileLabel.setText("")
        self.snippetDescription.setText("")
        self.edit.clear()
        self.tree.clearSelection()
        self.currentFile = ""

    def askSave(self):
        return QMessageBox.question(
            self, self.tr("Save?"),
            self.tr("Do you want to save changes to {}?").format(
                self.currentFileLabel.text()),
            QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)

    def reject(self):
        self.settings.setValue("ui/snippeteditor/geometry",
                               self.saveGeometry())

        if self.snippetChanged():
            save = self.askSave()
            if save == QMessageBox.Yes:
                self.save()
            elif save == QMessageBox.No:
                self.loadSnippet()
            elif save == QMessageBox.Cancel:
                return
        self.accept()

    def browseSnippets(self):
        url = QUrl.fromLocalFile(snippetPath)
        QDesktopServices.openUrl(url)

    def newFolder(self):
        (folderName, ok) = QInputDialog.getText(self, self.tr("Folder Name"),
                                                self.tr("Folder Name: "))
        if ok and folderName:
            index = self.tree.selectionModel().currentIndex()
            selection = self.files.filePath(index)
            if QFileInfo(selection).isDir():
                QDir(selection).mkdir(folderName)
            else:
                QDir(snippetPath).mkdir(folderName)

    def selectFile(self, new, old):
        if (self.resetting):
            self.resetting = False
            return
        if len(new.indexes()) == 0:
            self.clearSelection()
            self.currentFile = ""
            self.readOnly(True)
            return
        newSelection = self.files.filePath(new.indexes()[0])
        self.settings.setValue("ui/snippeteditor/selected", newSelection)
        if QFileInfo(newSelection).isDir():
            self.readOnly(True)
            self.clearSelection()
            self.currentFile = ""
            return

        if old and old.length() > 0:
            oldSelection = self.files.filePath(old.indexes()[0])
            if not QFileInfo(oldSelection).isDir() and self.snippetChanged():
                save = self.askSave()
                if save == QMessageBox.Yes:
                    self.save()
                elif save == QMessageBox.No:
                    pass
                elif save == QMessageBox.Cancel:
                    self.resetting = True
                    self.tree.selectionModel().select(
                        old, QItemSelectionModel.ClearAndSelect
                        | QItemSelectionModel.Rows)
                    return False

        self.currentFile = newSelection
        self.loadSnippet()

    def loadSnippet(self):
        self.currentFileLabel.setText(QFileInfo(self.currentFile).baseName())
        (snippetDescription, snippetKeys,
         snippetCode) = loadSnippetFromFile(self.currentFile)
        self.snippetDescription.setText(
            snippetDescription
        ) if snippetDescription else self.snippetDescription.setText("")
        self.keySequenceEdit.setKeySequence(
            snippetKeys
        ) if snippetKeys else self.keySequenceEdit.setKeySequence(
            QKeySequence(""))
        self.edit.setPlainText(
            snippetCode) if snippetCode else self.edit.setPlainText("")
        self.readOnly(False)

    def newFileDialog(self):
        (snippetName, ok) = QInputDialog.getText(self,
                                                 self.tr("Snippet Name"),
                                                 self.tr("Snippet Name: "),
                                                 flags=self.windowFlags())
        if ok and snippetName:
            if not snippetName.endswith(".py"):
                snippetName += ".py"
            index = self.tree.selectionModel().currentIndex()
            selection = self.files.filePath(index)
            if QFileInfo(selection).isDir():
                path = os.path.join(selection, snippetName)
            else:
                path = os.path.join(snippetPath, snippetName)
                self.readOnly(False)
            open(path, "w").close()
            self.tree.setCurrentIndex(self.files.index(path))
            log_debug("Snippet %s created." % snippetName)

    def readOnly(self, flag):
        self.keySequenceEdit.setEnabled(not flag)
        self.snippetDescription.setReadOnly(flag)
        self.edit.setReadOnly(flag)
        if flag:
            self.snippetDescription.setDisabled(True)
            self.edit.setDisabled(True)
        else:
            self.snippetDescription.setEnabled(True)
            self.edit.setEnabled(True)

    def deleteSnippet(self):
        selection = self.tree.selectedIndexes()[::self.columns][
            0]  #treeview returns each selected element in the row
        snippetName = self.files.fileName(selection)
        question = QMessageBox.question(
            self, self.tr("Confirm"),
            self.tr("Confirm deletion: ") + snippetName)
        if (question == QMessageBox.StandardButton.Yes):
            log_debug("Deleting snippet %s." % snippetName)
            self.clearSelection()
            self.files.remove(selection)
            self.registerAllSnippets()

    def snippetChanged(self):
        if (self.currentFile == "" or QFileInfo(self.currentFile).isDir()):
            return False
        (snippetDescription, snippetKeys,
         snippetCode) = loadSnippetFromFile(self.currentFile)
        if snippetKeys == None and not self.keySequenceEdit.keySequence(
        ).isEmpty():
            return True
        if snippetKeys != None and snippetKeys != self.keySequenceEdit.keySequence(
        ).toString():
            return True
        return self.edit.toPlainText() != snippetCode or \
               self.snippetDescription.text() != snippetDescription

    def save(self):
        log_debug("Saving snippet %s" % self.currentFile)
        outputSnippet = codecs.open(self.currentFile, "w", "utf-8")
        outputSnippet.write("#" + self.snippetDescription.text() + "\n")
        outputSnippet.write("#" +
                            self.keySequenceEdit.keySequence().toString() +
                            "\n")
        outputSnippet.write(self.edit.toPlainText())
        outputSnippet.close()
        self.registerAllSnippets()

    def run(self):
        if self.context == None:
            log_warn("Cannot run snippets outside of the UI at this time.")
            return
        if self.snippetChanged():
            self.save()
        actionText = actionFromSnippet(self.currentFile,
                                       self.snippetDescription.text())
        UIActionHandler.globalActions().executeAction(actionText, self.context)

        log_debug("Saving snippet %s" % self.currentFile)
        outputSnippet = codecs.open(self.currentFile, "w", "utf-8")
        outputSnippet.write("#" + self.snippetDescription.text() + "\n")
        outputSnippet.write("#" +
                            self.keySequenceEdit.keySequence().toString() +
                            "\n")
        outputSnippet.write(self.edit.toPlainText())
        outputSnippet.close()
        self.registerAllSnippets()

    def clearHotkey(self):
        self.keySequenceEdit.clear()
Exemplo n.º 3
0
class NovoCliente(QWidget):
    status_signal = Signal(str)

    def __init__(self):
        self.db = ClientesDB()
        QWidget.__init__(self)
        font = QFont()
        font.setBold(True)  # Labels em Negrito

        # Labels:
        self.label_title = QLabel("Novo Cliente")
        self.label_title.setFont(font)
        self.label_nome = QLabel("Nome Completo:")
        self.label_nome.setFont(font)
        self.label_endereco = QLabel("Endereço:")
        self.label_endereco.setFont(font)
        self.label_numero = QLabel("Número:")
        self.label_numero.setFont(font)
        self.label_cpf = QLabel("CPF:")
        self.label_cpf.setFont(font)

        # Entries:
        self.entry_nome = QLineEdit()
        self.entry_endereco = QTextEdit()
        self.entry_numero = QLineEdit()
        self.entry_cpf = QLineEdit()

        # Botões;
        self.button_salvar = QPushButton("&Salvar")
        self.button_salvar.clicked.connect(self.salvar_cliente)
        self.button_salvar.setShortcut("Ctrl+S")
        self.button_cancelar = QPushButton("Cancelar")
        self.button_cancelar.clicked.connect(self.limpar)
        self.button_cancelar.setShortcut("ESC")

        # Linha
        self.line = QFrame()
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.line.setLineWidth(0)
        self.line.setMidLineWidth(1)

        # Leiaute:
        self.layout = QVBoxLayout()
        self.layout_buttons = QHBoxLayout()
        self.layout.addWidget(self.label_title)
        self.layout.addWidget(self.line)
        self.layout.addWidget(self.label_nome)
        self.layout.addWidget(self.entry_nome)
        self.layout.addWidget(self.label_numero)
        self.layout.addWidget(self.entry_numero)
        self.layout.addWidget(self.label_cpf)
        self.layout.addWidget(self.entry_cpf)
        self.layout.addWidget(self.label_endereco)
        self.layout.addWidget(self.entry_endereco)
        self.layout_buttons.addWidget(self.button_salvar)
        self.layout_buttons.addWidget(self.button_cancelar)
        self.layout.addStretch(2)
        self.layout.addLayout(self.layout_buttons)
        self.setLayout(self.layout)

    @Slot()
    def salvar_cliente(self):
        nome = self.entry_nome.text()
        cpf = self.entry_cpf.text()
        numero = self.entry_numero.text()
        endereco = self.entry_endereco.toPlainText()
        data = {
            'nome': nome,
            'cpf': cpf,
            'numero': numero,
            'endereco': endereco
        }
        try:
            self.db.novo_cliente(data)
            self.status_signal.emit("Salvo")
            self.limpar()
        except ValueError as e:
            popup = QMessageBox(QMessageBox.Critical, "Erro", "Campo Inválido")
            popup.setInformativeText(str(e))
            popup.addButton(QMessageBox.Ok)
            popup.exec()

    @Slot()
    def limpar(self):
        self.entry_nome.setText('')
        self.entry_endereco.setText('')
        self.entry_numero.setText('')
        self.entry_cpf.setText('')