コード例 #1
0
ファイル: view.py プロジェクト: NJUaaron/ExcelAutoProcess
    def __init__( self ):
        # Initialize the super class
        super().__init__()
        self.model = Model(self)

        # About dialog initialization
        self.aboutDialog = QtWidgets.QDialog()
        self.ui2 = AboutDialog()
        self.ui2.setupUi(self.aboutDialog, assetPath)

        # Language select dialog initialization
        self.lanDialog = QtWidgets.QDialog()
        # IMPORTANT: ui3 have to be add self. Otherwise ui3 object will be recycled after __init__() 
        # Then the radio button can't response to the click
        self.ui3 = LanDialog(self, self.ui2)                 
        self.ui3.setupUi(self.lanDialog, assetPath)
コード例 #2
0
    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/mainPlug\icon.png'
        about_path = ':/plugins/mainPlug\\about.png'
        """self.add_action(
            icon_path,
            store_val=0,
            text=self.tr(u'PlotData'),
            callback=self.run,
            parent=self.iface.mainWindow())"""
        """self.add_action(
            icon_path,
            store_val=1,
            text=self.tr(u'File_Import_Test'),
            callback=self.run_file_input,
            dialog=FileInputDialog()
        )"""
        self.add_action(about_path,
                        store_val=2,
                        text=self.tr(u'About'),
                        callback=self.runabout,
                        dialog=AboutDialog())

        self.com.log("Add_action: About", 0)
        self.add_action(icon_path,
                        store_val=3,
                        text=self.tr(u'Calculate NDVI'),
                        callback=self.run_calc_ndvi,
                        dialog=ImportExportDialog())
        self.com.log("Add_Action: Calculate NDVI", 0)

        self.add_action(icon_path,
                        store_val=5,
                        text=self.tr(u'Plot Soil data'),
                        callback=self.run_SoilSample,
                        dialog=CsvInputdialog())

        self.add_action(icon_path,
                        store_val=4,
                        text=self.tr(u'Help'),
                        callback=self.run_help,
                        dialog=HelpDialog())

        self.add_action(icon_path,
                        store_val=6,
                        text=self.tr(u'Krig'),
                        callback=self.run_krig,
                        dialog=KrigDialog())
コード例 #3
0
 def slotHelpAbout(self):
     ad = AboutDialog(self)
     ad.show()
コード例 #4
0
class Historize(QObject):
    """This class handles the initialization and calls of the menus"""
    def __init__(self, iface):
        QObject.__init__(self)

        self.iface = iface
        self.dbconn = DBConn(iface)
        plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(plugin_dir, 'i18n',
                                   'Historize_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            translator = QTranslator()
            translator.load(locale_path)
            QCoreApplication.installTranslator(translator)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(translator)

    def initGui(self):
        self.menu = QMenu()
        self.menu.setTitle("Historize")

        self.layerMenu = QMenu()
        self.layerMenu.setTitle("Layer")

        # Create menu actions
        self.actionInitDB = QAction(self.tr(u"Initialize Database"),
                                    self.iface.mainWindow())
        self.actionInitLayer = QAction(self.tr(u"Initialize Layer"),
                                       self.iface.mainWindow())
        self.actionLayerUpdate = QAction(self.tr(u"Update Layer"),
                                         self.iface.mainWindow())
        self.actionLayerLoad = QAction(self.tr(u"Load Layer"),
                                       self.iface.mainWindow())
        self.actionAbout = QAction(self.tr(u"About"), self.iface.mainWindow())

        # Connect menu actions
        self.actionInitDB.triggered.connect(self.initialize_database)
        self.actionInitLayer.triggered.connect(self.initialize_layer)
        self.actionLayerLoad.triggered.connect(self.show_load_layer_dialog)
        self.actionLayerUpdate.triggered.connect(self.show_update_layer_dialog)
        self.actionAbout.triggered.connect(self.show_about_dialog)

        self.iface.legendInterface().currentLayerChanged.connect(
            self.enable_disable_gui)

        # Add actions to menu
        self.layerMenu.addActions([
            self.actionInitLayer, self.actionLayerLoad, self.actionLayerUpdate
        ])
        self.menu.addAction(self.actionInitDB)
        self.menu.addMenu(self.layerMenu)
        self.menu.addAction(self.actionAbout)
        self.menu.insertSeparator(self.actionAbout)
        menuBar = self.iface.mainWindow().menuBar()
        menuBar.addMenu(self.menu)

        # Disable unusable actions
        self.actionInitDB.setEnabled(False)
        self.actionInitLayer.setEnabled(False)
        self.actionLayerUpdate.setEnabled(False)
        self.actionLayerLoad.setEnabled(False)

    def unload(self):
        self.menu.deleteLater()

    def initialize_database(self):
        """Use Database info from layer and run historisation.sql on it."""

        selectedLayer = self.iface.activeLayer()
        provider = selectedLayer.dataProvider()

        if provider.name() != 'postgres':
            QMessageBox.warning(
                self.iface.mainWindow(), self.tr(u"Invalid Layer"),
                self.tr(u"Layer must be provided by postgres!"))
            return
        uri = QgsDataSourceURI(provider.dataSourceUri())
        conn = self.dbconn.connect_to_DB(uri)
        cur = conn.cursor()
        if conn is False:
            return

        result = QMessageBox.warning(
            self.iface.mainWindow(), self.tr(u"Initialize Historisation"),
            self.tr(u"Initialize historisation on this layers database?"),
            QMessageBox.No | QMessageBox.Yes)
        if result == QMessageBox.Yes:
            sqlPath = os.path.dirname(
                os.path.realpath(__file__)) + '/sql/historisierung.sql'
            try:
                # Ignore first three characters
                # which invalidate the SQL command
                cur.execute(open(sqlPath, "r").read())
                conn.commit()
                QMessageBox.warning(
                    self.iface.mainWindow(), self.tr(u"Success"),
                    self.tr(u"Database initialized successfully!"))
            except psycopg2.Error as e:
                conn.rollback()
                QMessageBox.warning(
                    self.iface.mainWindow(), self.tr(u"Error"),
                    self.tr(u"Couldn't initialize Database.\n" + e.message))
            conn.close()
            self.enable_disable_gui(selectedLayer)
        else:
            return

    def initialize_layer(self):
        """Use Layer info and run init() .sql query"""
        selectedLayer = self.iface.activeLayer()
        provider = selectedLayer.dataProvider()
        uri = QgsDataSourceURI(provider.dataSourceUri())
        conn = self.dbconn.connect_to_DB(uri)

        if conn is False:
            return

        result = QMessageBox.warning(
            self.iface.mainWindow(), self.tr(u"Initialize Layer"),
            self.tr(u"Are you sure you wish to proceed?"),
            QMessageBox.No | QMessageBox.Yes)
        if result == QMessageBox.Yes:
            # Get SQL vars
            hasGeometry = selectedLayer.hasGeometryType()
            schema = uri.schema()
            table = uri.table()

            execute = SQLExecute(self.iface, self.iface.mainWindow(), uri)
            success, msg = execute.Init_hist_tabs(hasGeometry, schema, table)
            if success:
                QMessageBox.warning(
                    self.iface.mainWindow(), self.tr(u"Success"),
                    self.tr(u"Layer successfully initialized!"))
            else:
                QMessageBox.warning(self.iface.mainWindow(), self.tr(u"Error"),
                                    self.tr(u"Initialization failed!\n" + msg))
            self.enable_disable_gui(selectedLayer)
        else:
            return

    def show_update_layer_dialog(self):
        """Open ImportUpdate dialog"""
        self.updateDialog = ImportUpdateDialog(self.iface)
        self.updateDialog.show()

    def show_load_layer_dialog(self):
        """Open selectDate dialog"""
        self.dateDialog = SelectDateDialog(self.iface)
        self.dateDialog.show()

    def show_about_dialog(self):
        """Show About dialog"""
        self.aboutDialog = AboutDialog()
        self.aboutDialog.show()

    def enable_disable_gui(self, layer):
        """Enable/Disable menu options based on selected layer"""
        self.actionInitDB.setEnabled(False)
        self.layerMenu.setEnabled(False)
        self.actionInitLayer.setEnabled(False)
        self.actionLayerUpdate.setEnabled(False)
        self.actionLayerLoad.setEnabled(False)

        selectedLayer = self.iface.activeLayer()
        if selectedLayer:
            provider = layer.dataProvider()

            if provider.name() == "postgres":
                self.actionInitDB.setEnabled(True)
                uri = QgsDataSourceURI(provider.dataSourceUri())
                execute = SQLExecute(self.iface, self.iface.mainWindow(), uri)
                historised = execute.check_if_historised(
                    uri.schema(),
                    self.iface.activeLayer().name())
                db_initialized = execute.db_initialize_check(uri.schema())

                if db_initialized:
                    self.actionInitDB.setEnabled(False)
                    self.layerMenu.setEnabled(True)
                else:
                    self.layerMenu.setEnabled(False)

                if historised:
                    self.actionLayerUpdate.setEnabled(True)
                    self.actionLayerLoad.setEnabled(True)
                else:
                    self.actionInitLayer.setEnabled(True)
コード例 #5
0
 def show_about_dialog(self):
     """Show About dialog"""
     self.aboutDialog = AboutDialog()
     self.aboutDialog.show()
コード例 #6
0
ファイル: view.py プロジェクト: NJUaaron/ExcelAutoProcess
class Ui_MainWindow(object):
    def __init__( self ):
        # Initialize the super class
        super().__init__()
        self.model = Model(self)

        # About dialog initialization
        self.aboutDialog = QtWidgets.QDialog()
        self.ui2 = AboutDialog()
        self.ui2.setupUi(self.aboutDialog, assetPath)

        # Language select dialog initialization
        self.lanDialog = QtWidgets.QDialog()
        # IMPORTANT: ui3 have to be add self. Otherwise ui3 object will be recycled after __init__() 
        # Then the radio button can't response to the click
        self.ui3 = LanDialog(self, self.ui2)                 
        self.ui3.setupUi(self.lanDialog, assetPath)
        

    def setupUi(self, MainWindow):
        self.MainWindow = MainWindow
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(524, 394)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(assetPath + 'icon.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off) # window icon
        MainWindow.setWindowIcon(icon)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.inputLayout = QtWidgets.QVBoxLayout()
        self.inputLayout.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
        self.inputLayout.setContentsMargins(-1, 10, -1, 20)
        self.inputLayout.setSpacing(20)
        self.inputLayout.setObjectName("inputLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setSpacing(10)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.sourceLabel = QtWidgets.QLabel(self.centralwidget)
        self.sourceLabel.setObjectName("sourceLabel")
        self.horizontalLayout.addWidget(self.sourceLabel)
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout.addWidget(self.lineEdit)

        self.browseButton1 = QtWidgets.QPushButton(self.centralwidget)
        self.browseButton1.setObjectName("browseButton1")
        self.browseButton1.clicked.connect(lambda: self.browseButtonClicked(1))   # bind click function
        
        self.horizontalLayout.addWidget(self.browseButton1)
        spacerItem = QtWidgets.QSpacerItem(30, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.sheetSelect1 = QtWidgets.QComboBox(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sheetSelect1.sizePolicy().hasHeightForWidth())
        self.sheetSelect1.setSizePolicy(sizePolicy)
        self.sheetSelect1.setMinimumSize(QtCore.QSize(90, 0))
        self.sheetSelect1.setObjectName("sheetSelect1")
        self.horizontalLayout.addWidget(self.sheetSelect1)
        self.inputLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setSpacing(10)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.targetLabel = QtWidgets.QLabel(self.centralwidget)
        self.targetLabel.setObjectName("targetLabel")
        self.horizontalLayout_2.addWidget(self.targetLabel)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.horizontalLayout_2.addWidget(self.lineEdit_2)

        self.browseButton2 = QtWidgets.QPushButton(self.centralwidget)
        self.browseButton2.setObjectName("browseButton2")
        self.browseButton2.clicked.connect(lambda: self.browseButtonClicked(2))   # bind click function

        self.horizontalLayout_2.addWidget(self.browseButton2)
        spacerItem1 = QtWidgets.QSpacerItem(30, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem1)
        self.sheetSelect2 = QtWidgets.QComboBox(self.centralwidget)
        self.sheetSelect2.setMinimumSize(QtCore.QSize(90, 0))
        self.sheetSelect2.setObjectName("sheetSelect2")
        self.horizontalLayout_2.addWidget(self.sheetSelect2)
        self.inputLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setSpacing(10)
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.headerNameLabel = QtWidgets.QLabel(self.centralwidget)
        self.headerNameLabel.setObjectName("headerNameLabel")
        self.horizontalLayout_3.addWidget(self.headerNameLabel)
        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.horizontalLayout_3.addWidget(self.lineEdit_3)
        spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem2)

        self.startButton = QtWidgets.QPushButton(self.centralwidget)
        self.startButton.setObjectName("startButton")
        self.startButton.clicked.connect(self.start)   # bind click function

        self.horizontalLayout_3.addWidget(self.startButton)
        self.inputLayout.addLayout(self.horizontalLayout_3)
        self.verticalLayout_4.addLayout(self.inputLayout)
        self.logLabel = QtWidgets.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(11)
        self.logLabel.setFont(font)
        self.logLabel.setTextFormat(QtCore.Qt.AutoText)
        self.logLabel.setObjectName("logLabel")
        self.verticalLayout_4.addWidget(self.logLabel)

        self.logBrowser = QtWidgets.QTextBrowser(self.centralwidget)
        self.logBrowser.setObjectName("logBrowser")

        self.verticalLayout_4.addWidget(self.logBrowser)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 524, 23))
        self.menubar.setObjectName("menubar")
        self.menuPreference = QtWidgets.QMenu(self.menubar)
        self.menuPreference.setObjectName("menuPreference")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionLanguage = QtWidgets.QAction(MainWindow)
        self.actionLanguage.setObjectName("actionLanguage")
        self.actionLanguage.triggered.connect(self.openLanDialog)    # bind trigger
        self.actionClearLog = QtWidgets.QAction(MainWindow)
        self.actionClearLog.setObjectName("actionClearLog")
        self.actionClearLog.triggered.connect(self.clearLog)    # bind trigger
        self.actionAbout = QtWidgets.QAction(MainWindow)
        self.actionAbout.setObjectName("actionAbout")
        self.actionAbout.triggered.connect(self.openAboutDialog)    # bind trigger
        self.menuPreference.addAction(self.actionLanguage)
        self.menuPreference.addAction(self.actionClearLog)
        self.menuPreference.addSeparator()
        self.menuPreference.addAction(self.actionAbout)
        self.menubar.addAction(self.menuPreference.menuAction())

        self.retranslateUi(2)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, lan):
        if lan == 1:
            self.MainWindow.setWindowTitle("Excel 自动处理工具")
            self.MainWindow.setStatusTip("欢迎!")
            self.sourceLabel.setText("源文件")
            self.browseButton1.setText("浏览")
            self.targetLabel.setText("目标文件")
            self.browseButton2.setText("浏览")
            self.headerNameLabel.setText("关键表头名")
            self.startButton.setText("开始")
            self.logLabel.setText("日志")
            self.menuPreference.setTitle("设置")
            self.actionLanguage.setText("语言")
            self.actionClearLog.setText("清空日志")
            self.actionAbout.setText("关于")
        else:
            self.MainWindow.setWindowTitle("Excel Auto Processor")
            self.MainWindow.setStatusTip("Welcome!")
            self.sourceLabel.setText("Source File")
            self.browseButton1.setText("Browse")
            self.targetLabel.setText("Target File")
            self.browseButton2.setText("Browse")
            self.headerNameLabel.setText("Key Column Header Name")
            self.startButton.setText("Start")
            self.logLabel.setText("Log")
            self.menuPreference.setTitle("Setting")
            self.actionLanguage.setText("Language")
            self.actionClearLog.setText("Clear Log")
            self.actionAbout.setText("About")

    def debugPrint( self, msgType, msg ):   #1:info  #2: warning  #3: error
        '''Print the message in the text edit at the bottom of the
        horizontal splitter.
        '''
        if msgType == 1:
            self.logBrowser.append( '<strong style="color:#43ba1e;">[INFO]</strong> ' + msg )    # Green
        elif msgType == 2:
            self.logBrowser.append( '<strong style="color:#aa7a19;">[WARNING]</strong> ' + msg )    # Yello
        else:
            self.logBrowser.append( '<strong style="color:#da3211;">[ERROR]</strong> ' + msg )      # Red
    
    def clearLog(self):
        # Clear log information in log browser
        self.logBrowser.clear()
    
    def openLanDialog(self):
        self.lanDialog.show()
    
    def openAboutDialog(self):
        self.aboutDialog.show()

    
    def browseButtonClicked(self, type):    # type = 1 or 2
        fileName = self.browseFile()
        if fileName:
            sheetNames = self.model.readSheetName(fileName, type)   # a sheet name set
            if type == 1:  
                self.debugPrint( 1, "Set source file name: " + fileName )
                self.lineEdit.setText(fileName)
                self.setComboBox(sheetNames, self.sheetSelect1)
            else:
                self.debugPrint( 1, "Set target file name: " + fileName )
                self.lineEdit_2.setText(fileName)
                self.setComboBox(sheetNames, self.sheetSelect2)

    
    def resetComboBox(self, comboBox):
        # delete all items in comboBox
        while comboBox.count() > 0:
            self.sheetSelect1.removeItem(0)


    def setComboBox(self, items, comboBox):    
        self.resetComboBox(comboBox)
        if len(items) > 1:
            comboBox.addItem('All sheets')
        for item in items:
            comboBox.addItem(str(item))

    
    def browseFile(self):
        # 打开文件目录窗口,选取文件
        options = QtWidgets.QFileDialog.Options()
        options |= QtWidgets.QFileDialog.DontUseNativeDialog
        fileName, _ = QtWidgets.QFileDialog.getOpenFileName(
                        None,
                        "QFileDialog.getOpenFileName()",
                        "",
                        "WPS Excel文档 (*.xls);;Office Excel文档 (*.xlsx)",
                        options=options)
        return fileName
    
    def start(self):
        # Check if input is empty
        selectedSheet1 = self.sheetSelect1.currentText()
        if not selectedSheet1:
            self.debugPrint( 2, "Please select source file and its sheet" )
            return
        
        selectedSheet2 = self.sheetSelect2.currentText()
        if not selectedSheet2:
            self.debugPrint( 2, "Please select target file and its sheet" )
            return
        
        keyColumn = self.lineEdit_3.text()
        if not keyColumn:
            self.debugPrint( 2, "Please type in key column header name" )
            return

        self.model.process(keyColumn, selectedSheet1, selectedSheet2)
コード例 #7
0
ファイル: main.py プロジェクト: bluthen/PasswordManager
    def __init__(self, app):
        QtWidgets.QMainWindow.__init__(self)
        self.app = app
        self.clipboard = QtWidgets.QApplication.clipboard()

        self.setWindowTitle("Password Manager")

        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileOpen = QtWidgets.QAction("&Open",
                                          self.fileMenu,
                                          shortcut=QtGui.QKeySequence.Open,
                                          triggered=self.slotFileOpen)
        self.fileMenu.addAction(self.fileOpen)
        self.fileSave = QtWidgets.QAction("&Save",
                                          self.fileMenu,
                                          shortcut=QtGui.QKeySequence.Save,
                                          triggered=self.slotFileSave)
        self.fileMenu.addAction(self.fileSave)
        self.fileSaveAs = QtWidgets.QAction("Save &As...",
                                            self.fileMenu,
                                            shortcut=QtGui.QKeySequence.SaveAs,
                                            triggered=self.slotFileSaveAs)
        self.fileMenu.addAction(self.fileSaveAs)
        self.fileMenu.addSeparator()
        self.fileImportCSV = QtWidgets.QAction(
            "&Import CSV...", self.fileMenu, triggered=self.slotFileImportCSV)
        self.fileMenu.addAction(self.fileImportCSV)
        self.fileMenu.addSeparator()
        self.fileSettings = QtWidgets.QAction("S&ettings",
                                              self.fileMenu,
                                              triggered=self.slotSettings)
        self.fileMenu.addAction(self.fileSettings)
        self.fileMenu.addSeparator()
        self.fileQuit = QtWidgets.QAction(
            "&Quit",
            self.fileMenu,
            shortcut=QtGui.QKeySequence.mnemonic("&Quit"),
            triggered=self.slotQuit)
        self.fileMenu.addAction(self.fileQuit)

        self.viewMenu = self.menuBar().addMenu("&View")
        self.viewPasswords = QtWidgets.QAction(
            "Show &Passwords", self.viewMenu, triggered=self.slotViewPasswords)
        self.viewPasswords.setCheckable(True)
        self.viewMenu.addAction(self.viewPasswords)
        self.viewMenu.addSeparator()
        self.viewFind = QtWidgets.QAction("Find...",
                                          self.viewMenu,
                                          triggered=self.slotViewFind)
        self.viewMenu.addAction(self.viewFind)

        self.entryMenu = self.menuBar().addMenu("&Entry")
        self.entryMenu.aboutToShow.connect(self.slotEntryMenuAboutToShow)
        self.entryCopyU = QtWidgets.QAction("Copy Username to Clipboard",
                                            self.entryMenu,
                                            triggered=self.slotEntryCopyU)
        self.entryMenu.addAction(self.entryCopyU)
        self.entryCopyP = QtWidgets.QAction("Copy Password to Clipboard",
                                            self.entryMenu,
                                            triggered=self.slotEntryCopyP)
        self.entryMenu.addAction(self.entryCopyP)
        self.entryMenu.addSeparator()

        # Detect if an X system
        if os.name == 'posix':  # Is there a better way?
            self.entryCopyUS = QtWidgets.QAction(
                "Copy Username to Selection",
                self.entryMenu,
                triggered=self.slotEntryCopyUS)
            self.entryMenu.addAction(self.entryCopyUS)
            self.entryCopyPS = QtWidgets.QAction(
                "Copy Password to Selection",
                self.entryMenu,
                triggered=self.slotEntryCopyPS)
            self.entryMenu.addAction(self.entryCopyPS)
            self.entryMenu.addSeparator()

        self.entryNew = QtWidgets.QAction("New Entry",
                                          self.entryMenu,
                                          triggered=self.slotEntryNew)
        self.entryMenu.addAction(self.entryNew)
        self.entryEdit = QtWidgets.QAction("Edit Entry",
                                           self.entryMenu,
                                           triggered=self.slotEntryEdit)
        self.entryMenu.addAction(self.entryEdit)
        self.entryDel = QtWidgets.QAction("Delete Entry",
                                          self.entryMenu,
                                          triggered=self.slotEntryDelete)
        self.entryMenu.addAction(self.entryDel)
        self.entryEdit.setEnabled(False)
        self.entryDel.setEnabled(False)
        self.entryCopyU.setEnabled(False)
        self.entryCopyP.setEnabled(False)

        self.helpMenu = self.menuBar().addMenu("&Help")
        self.helpAbout = QtWidgets.QAction("&About",
                                           self.helpMenu,
                                           triggered=self.slotHelpAbout)
        self.helpMenu.addAction(self.helpAbout)

        self.table = QtWidgets.QTableView()
        self.table.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.table.verticalHeader().setDefaultSectionSize(20)
        self.table.horizontalHeader().setStretchLastSection(True)
        self.table.customContextMenuRequested.connect(self.doTableContextMenu)
        self.document = Document()
        self.mymodel = MainTableModel(self.document, self)
        self.table.setModel(self.mymodel)
        self.table.setSortingEnabled(True)
        self.table.setCornerButtonEnabled(False)
        self.table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.table.setSelectionMode(
            QtWidgets.QAbstractItemView.SingleSelection)
        self.setCentralWidget(self.table)

        self.configDialog = ConfigDialog(self)

        self.editDialog = EditDialog(self, self.document, self.mymodel)
        self.delDialog = DelDialog(self, self.document)
        self.openConfirmDialog = ConfirmDialog(
            self, "Open without saving?",
            "Open new file without saving current document?")
        self.importCSVDialog = ImportCSVDialog(self, self.document,
                                               self.mymodel)
        self.helpAboutDialog = AboutDialog(self)
        self.quitConfirmDialog = ConfirmDialog(
            self, "Quit without saving?",
            "Quit without saving current document?")

        self.findDialog = FindDialog(self, self.table, self.document)

        self.viewFindShortcut = QtWidgets.QShortcut(QtGui.QKeySequence.Find,
                                                    self)
        self.viewFindShortcut.activated.connect(self.slotViewFind)
        self.viewFindNextShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence.FindNext, self)
        self.viewFindNextShortcut.activated.connect(self.slotViewFindNext)
        self.viewFindPreviousShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence.FindPrevious, self)
        self.viewFindPreviousShortcut.activated.connect(
            self.slotViewFindPrevious)

        self.dialogFindNextShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence.FindNext, self.findDialog)
        self.dialogFindNextShortcut.activated.connect(self.slotViewFindNext)
        self.dialogFindPreviousShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence.FindPrevious, self.findDialog)
        self.dialogFindPreviousShortcut.activated.connect(
            self.slotViewFindPrevious)

        app.aboutToQuit.connect(self.slotAboutToQuit)

        size = Config().getGeometry()
        self.resize(size)

        self.table.horizontalHeader().resizeSection(0,
                                                    Config().getGeometryH0())
        self.table.horizontalHeader().resizeSection(1,
                                                    Config().getGeometryH1())
        self.table.horizontalHeader().resizeSection(2,
                                                    Config().getGeometryH2())

        self.firstShow = False
コード例 #8
0
ファイル: main.py プロジェクト: bluthen/PasswordManager
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, app):
        QtWidgets.QMainWindow.__init__(self)
        self.app = app
        self.clipboard = QtWidgets.QApplication.clipboard()

        self.setWindowTitle("Password Manager")

        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileOpen = QtWidgets.QAction("&Open",
                                          self.fileMenu,
                                          shortcut=QtGui.QKeySequence.Open,
                                          triggered=self.slotFileOpen)
        self.fileMenu.addAction(self.fileOpen)
        self.fileSave = QtWidgets.QAction("&Save",
                                          self.fileMenu,
                                          shortcut=QtGui.QKeySequence.Save,
                                          triggered=self.slotFileSave)
        self.fileMenu.addAction(self.fileSave)
        self.fileSaveAs = QtWidgets.QAction("Save &As...",
                                            self.fileMenu,
                                            shortcut=QtGui.QKeySequence.SaveAs,
                                            triggered=self.slotFileSaveAs)
        self.fileMenu.addAction(self.fileSaveAs)
        self.fileMenu.addSeparator()
        self.fileImportCSV = QtWidgets.QAction(
            "&Import CSV...", self.fileMenu, triggered=self.slotFileImportCSV)
        self.fileMenu.addAction(self.fileImportCSV)
        self.fileMenu.addSeparator()
        self.fileSettings = QtWidgets.QAction("S&ettings",
                                              self.fileMenu,
                                              triggered=self.slotSettings)
        self.fileMenu.addAction(self.fileSettings)
        self.fileMenu.addSeparator()
        self.fileQuit = QtWidgets.QAction(
            "&Quit",
            self.fileMenu,
            shortcut=QtGui.QKeySequence.mnemonic("&Quit"),
            triggered=self.slotQuit)
        self.fileMenu.addAction(self.fileQuit)

        self.viewMenu = self.menuBar().addMenu("&View")
        self.viewPasswords = QtWidgets.QAction(
            "Show &Passwords", self.viewMenu, triggered=self.slotViewPasswords)
        self.viewPasswords.setCheckable(True)
        self.viewMenu.addAction(self.viewPasswords)
        self.viewMenu.addSeparator()
        self.viewFind = QtWidgets.QAction("Find...",
                                          self.viewMenu,
                                          triggered=self.slotViewFind)
        self.viewMenu.addAction(self.viewFind)

        self.entryMenu = self.menuBar().addMenu("&Entry")
        self.entryMenu.aboutToShow.connect(self.slotEntryMenuAboutToShow)
        self.entryCopyU = QtWidgets.QAction("Copy Username to Clipboard",
                                            self.entryMenu,
                                            triggered=self.slotEntryCopyU)
        self.entryMenu.addAction(self.entryCopyU)
        self.entryCopyP = QtWidgets.QAction("Copy Password to Clipboard",
                                            self.entryMenu,
                                            triggered=self.slotEntryCopyP)
        self.entryMenu.addAction(self.entryCopyP)
        self.entryMenu.addSeparator()

        # Detect if an X system
        if os.name == 'posix':  # Is there a better way?
            self.entryCopyUS = QtWidgets.QAction(
                "Copy Username to Selection",
                self.entryMenu,
                triggered=self.slotEntryCopyUS)
            self.entryMenu.addAction(self.entryCopyUS)
            self.entryCopyPS = QtWidgets.QAction(
                "Copy Password to Selection",
                self.entryMenu,
                triggered=self.slotEntryCopyPS)
            self.entryMenu.addAction(self.entryCopyPS)
            self.entryMenu.addSeparator()

        self.entryNew = QtWidgets.QAction("New Entry",
                                          self.entryMenu,
                                          triggered=self.slotEntryNew)
        self.entryMenu.addAction(self.entryNew)
        self.entryEdit = QtWidgets.QAction("Edit Entry",
                                           self.entryMenu,
                                           triggered=self.slotEntryEdit)
        self.entryMenu.addAction(self.entryEdit)
        self.entryDel = QtWidgets.QAction("Delete Entry",
                                          self.entryMenu,
                                          triggered=self.slotEntryDelete)
        self.entryMenu.addAction(self.entryDel)
        self.entryEdit.setEnabled(False)
        self.entryDel.setEnabled(False)
        self.entryCopyU.setEnabled(False)
        self.entryCopyP.setEnabled(False)

        self.helpMenu = self.menuBar().addMenu("&Help")
        self.helpAbout = QtWidgets.QAction("&About",
                                           self.helpMenu,
                                           triggered=self.slotHelpAbout)
        self.helpMenu.addAction(self.helpAbout)

        self.table = QtWidgets.QTableView()
        self.table.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.table.verticalHeader().setDefaultSectionSize(20)
        self.table.horizontalHeader().setStretchLastSection(True)
        self.table.customContextMenuRequested.connect(self.doTableContextMenu)
        self.document = Document()
        self.mymodel = MainTableModel(self.document, self)
        self.table.setModel(self.mymodel)
        self.table.setSortingEnabled(True)
        self.table.setCornerButtonEnabled(False)
        self.table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.table.setSelectionMode(
            QtWidgets.QAbstractItemView.SingleSelection)
        self.setCentralWidget(self.table)

        self.configDialog = ConfigDialog(self)

        self.editDialog = EditDialog(self, self.document, self.mymodel)
        self.delDialog = DelDialog(self, self.document)
        self.openConfirmDialog = ConfirmDialog(
            self, "Open without saving?",
            "Open new file without saving current document?")
        self.importCSVDialog = ImportCSVDialog(self, self.document,
                                               self.mymodel)
        self.helpAboutDialog = AboutDialog(self)
        self.quitConfirmDialog = ConfirmDialog(
            self, "Quit without saving?",
            "Quit without saving current document?")

        self.findDialog = FindDialog(self, self.table, self.document)

        self.viewFindShortcut = QtWidgets.QShortcut(QtGui.QKeySequence.Find,
                                                    self)
        self.viewFindShortcut.activated.connect(self.slotViewFind)
        self.viewFindNextShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence.FindNext, self)
        self.viewFindNextShortcut.activated.connect(self.slotViewFindNext)
        self.viewFindPreviousShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence.FindPrevious, self)
        self.viewFindPreviousShortcut.activated.connect(
            self.slotViewFindPrevious)

        self.dialogFindNextShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence.FindNext, self.findDialog)
        self.dialogFindNextShortcut.activated.connect(self.slotViewFindNext)
        self.dialogFindPreviousShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence.FindPrevious, self.findDialog)
        self.dialogFindPreviousShortcut.activated.connect(
            self.slotViewFindPrevious)

        app.aboutToQuit.connect(self.slotAboutToQuit)

        size = Config().getGeometry()
        self.resize(size)

        self.table.horizontalHeader().resizeSection(0,
                                                    Config().getGeometryH0())
        self.table.horizontalHeader().resizeSection(1,
                                                    Config().getGeometryH1())
        self.table.horizontalHeader().resizeSection(2,
                                                    Config().getGeometryH2())

        self.firstShow = False

    def showEvent(self, e):
        e.ignore()
        if not self.firstShow:
            self.firstShow = True
            QtCore.QTimer.singleShot(10, self.loadLast)

    def loadLast(self):
        # Load up last file
        if Config().getOpenLast():
            self.slotFileOpen(fileName=Config().getOpenLastFile())

    def closeEvent(self, event):
        if self.document.isModified(
        ) and self.quitConfirmDialog.exec_() != QtWidgets.QDialog.Accepted:
            event.ignore()
            return
        app.quit()

    def customEvent(self, event):
        QtWidgets.QMessageBox.critical(self, "PasswordManager Error",
                                       event.getMessage())

    def slotQuit(self):
        self.app.postEvent(self, QtGui.QCloseEvent())

    def slotAboutToQuit(self):
        Config().setGeometry(self.size())
        Config().setGeometryH0(self.table.horizontalHeader().sectionSize(0))
        Config().setGeometryH1(self.table.horizontalHeader().sectionSize(1))
        Config().setGeometryH2(self.table.horizontalHeader().sectionSize(2))

    def slotHelpAbout(self):
        self.helpAboutDialog.show()

    def getSelRow(self):
        return self.table.selectedIndexes()[0].row()

    def slotFileOpen(self, checked=False, fileName=None):
        if fileName is None:
            fileName = QtWidgets.QFileDialog.getOpenFileName(
                self, "Open File", "", "Encrypted CSV (*.gcsv *.csv)", None,
                QtWidgets.QFileDialog.DontUseNativeDialog)[0]
        if fileName is None or len(fileName) == 0:
            return
        url = URL(fullpath=str(fileName))
        if not url.empty():
            if self.document.isModified(
            ) and self.openConfirmDialog.exec_() != QtWidgets.QDialog.Accepted:
                return
            try:
                self.mymodel.layoutAboutToBeChanged.emit()
                self.document.load(url.get_fullpath())
                self.mymodel.resort()
                self.mymodel.layoutChanged.emit()
                self.setWindowTitle("Password Manager - " + url.get_fullpath())
            except Exception as e:
                ok = OKDialog(self, "Problem opening file", e.__str__())
                traceback.print_exc(file=sys.stdout)
                ok.show()

    def slotFileSave(self):
        if self.document.getFile() is None:
            self.slotFileSaveAs()
        else:
            try:
                self.document.save(self.document.getFile())
            except Exception as e:
                ok = OKDialog(self, "Problem saving file", e.__str__())
                traceback.print_exc(file=sys.stdout)
                ok.show()

    def slotFileSaveAs(self):
        try:
            fileName = QtWidgets.QFileDialog.getSaveFileName(
                self, "Save File", "", "Encrypted CSV (*.gcsv *.csv)", None,
                QtWidgets.QFileDialog.DontUseNativeDialog)[0]
            if fileName is None or len(fileName) == 0:
                return
            url = URL(fullpath=str(fileName))
            if not url.empty():
                self.document.save(url.get_fullpath())
        except Exception as e:
            ok = OKDialog(self, "Problem saving file", e.__str__())
            traceback.print_exc(file=sys.stdout)
            ok.show()

    def slotFileImportCSV(self):
        fileName = QtWidgets.QFileDialog.getOpenFileName(
            self, "Import CSV", "", "Comma Seperated Value File (*.csv)", None,
            QtWidgets.QFileDialog.DontUseNativeDialog)[0]

        if fileName is None or len(fileName) == 0:
            return
        url = URL(fullpath=str(fileName))
        if not url.empty():
            self.importCSVDialog.setFile(url.get_fullpath())
            self.importCSVDialog.show()

    def slotEntryNew(self):
        self.editDialog.clear()
        self.editDialog.show()

    def slotEntryEdit(self):
        self.editDialog.setRow(self.getSelRow())
        self.editDialog.show()

    def slotEntryDelete(self):
        self.delDialog.setRow(self.getSelRow())
        if self.delDialog.exec_() == QtWidgets.QDialog.Accepted:
            del self.document.getData()[self.getSelRow()]
            self.document.setModified()

    def slotEntryCopyU(self):
        self.clipboard.setText(self.document.getData()[self.getSelRow()][1])

    def slotEntryCopyP(self):
        self.clipboard.setText(self.document.getData()[self.getSelRow()][2])

    def slotEntryCopyUS(self):
        self.clipboard.setText(self.document.getData()[self.getSelRow()][1],
                               QtGui.QClipboard.Selection)

    def slotEntryCopyPS(self):
        self.clipboard.setText(self.document.getData()[self.getSelRow()][2],
                               QtGui.QClipboard.Selection)

    def slotSettings(self):
        self.configDialog.show()

    def slotViewFind(self):
        self.findDialog.hide()
        self.findDialog.show()
        self.findDialog.findText.setFocus(QtCore.Qt.ActiveWindowFocusReason)
        self.findDialog.findText.setSelection(
            0, len(str(self.findDialog.findText.text())))
        self.findDialog.next.setDefault(True)

    def slotViewFindNext(self):
        self.findDialog.show()
        self.findDialog.slotNext()

    def slotViewFindPrevious(self):
        self.findDialog.slotPrevious()

    def slotViewPasswords(self, checked):
        self.mymodel.layoutChanged.emit()

    def slotEntryMenuAboutToShow(self):
        if len(self.table.selectedIndexes()) > 0:
            self.entryEdit.setEnabled(True)
            self.entryDel.setEnabled(True)
            self.entryCopyU.setEnabled(True)
            self.entryCopyP.setEnabled(True)
            self.entryCopyUS.setEnabled(True)
            self.entryCopyPS.setEnabled(True)
        else:
            self.entryEdit.setEnabled(False)
            self.entryDel.setEnabled(False)
            self.entryCopyU.setEnabled(False)
            self.entryCopyP.setEnabled(False)
            self.entryCopyUS.setEnabled(False)
            self.entryCopyPS.setEnabled(False)

    def doTableContextMenu(self, point):
        self.entryMenu.exec_(QtGui.QCursor.pos())