def __init__(self):
        super(HmiLogViewer, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.aboutDialog = MyAboutDialog(self)

        self.model = None
        self.parserConfig = {'headers': None, 'cols': None}
        self.projectId = ""

        # Menu entries actions
        QtCore.QObject.connect(self.ui.actionOpen,
                               QtCore.SIGNAL("triggered()"), self.openFile)
        QtCore.QObject.connect(self.ui.actionAddFile,
                               QtCore.SIGNAL("triggered()"),
                               lambda: self.openFile(True))
        QtCore.QObject.connect(self.ui.actionClose,
                               QtCore.SIGNAL("triggered()"), self.closeFile)
        QtCore.QObject.connect(self.ui.actionSaveAs,
                               QtCore.SIGNAL("triggered()"), self.saveFile)
        QtCore.QObject.connect(self.ui.actionImportConfigFile,
                               QtCore.SIGNAL("triggered()"),
                               self.importConfigFile)
        QtCore.QObject.connect(self.ui.actionAbout,
                               QtCore.SIGNAL("triggered()"),
                               self.aboutDialog.open)
        # Tool buttons actions
        QtCore.QObject.connect(self.ui.toolBtnOpen, QtCore.SIGNAL("clicked()"),
                               self.openFile)
        QtCore.QObject.connect(self.ui.toolBtnAppend,
                               QtCore.SIGNAL("clicked()"),
                               lambda: self.openFile(True))
        QtCore.QObject.connect(self.ui.toolBtnSave, QtCore.SIGNAL("clicked()"),
                               self.saveFile)
Exemple #2
0
class gui:

    def __init__(self):
# declarações da interface gráfica
        print("Gerando a interface gráfica")

        self.app = QApplication(sys.argv)

# janela principal
        self.wMain = QMainWindow()
        self.ui = Main()
        self.ui.setupUi(self.wMain)        
        
# seta a mesma folha de estilos e bloqueio para todas as janelas

        tema = sass.compile(filename="ui/style.scss")
        print("Gera o tema", tema)

        for janela in [
            self.wMain            
        ]:
            janela.setStyleSheet(tema)
            janela.setWindowModality(Qt.ApplicationModal)       

# inicializa a janela
        self.wMain.show()
 def __init__(self):
     super(SerialProgramLoader, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.loaderFrameLayout = QVBoxLayout(self.ui.loaderFrame)
     self.ui.loaderFrameLayout.setMargin(0)
     self.ui.loaderFrame.setLayout(self.ui.loaderFrameLayout)
     self.ui.loader = Loader(self)
     self.ui.loaderFrameLayout.addWidget(self.ui.loader)
def main():
    # This is only used for Pycharm to close the application when you only want to build the dependencies
    if len(sys.argv) > 1 and sys.argv[1] == '--build-only':
        print("Build successful!")
        return

    # Create the application object
    app = QApplication(sys.argv)

    # Create the main window
    main_window = QMainWindow()

    # Set icon
    icon = QtGui.QIcon()
    icon.addPixmap(QtGui.QPixmap(":/Icons/logo.ico"), QtGui.QIcon.Normal,
                   QtGui.QIcon.Off)
    main_window.setWindowIcon(icon)

    # Load the custom UI settings from QtDesigner into the main window
    ui = Ui_MainWindow()
    ui.setupUi(main_window)

    main_window.statusBar().hide()

    # Set the version number
    version_str = ".".join([str(x) for x in version])
    ui.versionLabel.setText(f"Remote Play Anything v{version_str}" +
                            ("" if len(sys.argv) <= 1 else
                             f", with args: {' '.join(sys.argv[1:])}"))

    # Initialize the list of games
    game_list = GameList(ui)

    # Add click events to all the buttons
    ui.startGameButton.clicked.connect(game_list.start_game)
    ui.addGameButton.clicked.connect(game_list.add_game)
    ui.editGameButton.clicked.connect(game_list.edit_game)
    ui.removeGameButton.clicked.connect(game_list.remove_game)
    ui.moveGameUpButton.clicked.connect(game_list.move_game_up)
    ui.moveGameDownButton.clicked.connect(game_list.move_game_down)
    ui.gamesList.clicked.connect(game_list.select_game)

    # Hide move button for now
    ui.moveGameUpButton.hide()
    ui.moveGameDownButton.hide()

    # Set the size of the window to fixed
    main_window.statusBar().setSizeGripEnabled(False)
    main_window.setFixedSize(main_window.size())

    # Finally show the window
    main_window.show()

    # Exit the app after closing the window
    sys.exit(app.exec_())
Exemple #5
0
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.userInfo = None
        self.setupUi(self)
        self.setWindowTitle("哔咔漫画")
        self.msgForm = QtBubbleLabel(self)

        self.qtTask = QtTask()

        icon = QIcon()
        pic = QPixmap()
        pic.loadFromData(resources.DataMgr.GetData("logo_round"))
        icon.addPixmap(pic, QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.aboutForm = QtAbout(self)

        self.searchForm = QtSearch(self)
        self.favoriteForm = QtFavorite(self)
        self.downloadForm = QtDownload(self)
        self.categoryForm = QtCategory(self)
        self.loadingForm = QtLoading(self)
        self.rankForm = QtRank(self)

        self.loginForm = QtLogin(self)
        self.registerForm = QtRegister(self)

        self.historyForm = QtHistory(self)

        self.qtReadImg = QtReadImg(self)

        self.userForm = QtUser(self)
        self.bookInfoForm = QtBookInfo(self)

        self.task = QtTask()
        self.task.SetOwner(self)
        self.timer = QTimer(self)
        self.timer.setInterval(100)
        # self.timer.timeout.connect(self.OnTimeOut)
        # self.timer.start()

        self.stackedWidget.addWidget(self.loginForm)
        self.stackedWidget.addWidget(self.userForm)

        self.settingForm = QtSetting(self)
        self.settingForm.LoadSetting()

        self.resize(self.settingForm.mainSize)
        self.bookInfoForm.resize(self.settingForm.bookSize)
        self.loginForm.userIdEdit.setText(self.settingForm.userId)
        self.loginForm.passwdEdit.setText(self.settingForm.passwd)

        self.menusetting.triggered.connect(self.OpenSetting)
        self.menuabout.triggered.connect(self.OpenAbout)
class OpcDataTrender(QtGui.QMainWindow):
    def __init__(self):
        super(OpcDataTrender, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.aboutDialog = MyAboutDialog(self)

        self.samples = []

        try:
            self.opc = OPCHandler()
        except OpenOPC.OPCError, error_msg:
            self.opc = None
            QtGui.QMessageBox.question(self.ui.centralwidget,
                                       u"OPC Error",
                                       u"Failed to open a connection to OPC server :\n%s" % error_msg,
                                       QtGui.QMessageBox.Ok)
            exit()

        self.timer = QtCore.QTimer()
        self.startTimestamp = 0

        ###########
        # Threads #
        ###########
        # OPC reading thread
        self.opcThread = OPCReadingThread()
        self.opcThread.dataReady.connect(self.getData, QtCore.Qt.QueuedConnection)

        QtCore.QObject.connect(self.ui.actionAddTag,
                               QtCore.SIGNAL("triggered()"),
                               self.addTag)
        QtCore.QObject.connect(self.ui.actionAbout,
                               QtCore.SIGNAL("triggered()"),
                               self.aboutDialog.open)

        QtCore.QObject.connect(QtCore.QCoreApplication.instance(),
                               QtCore.SIGNAL("aboutToQuit()"),
                               self.quit)

        QtCore.QObject.connect(self.ui.startBtn,
                               QtCore.SIGNAL("clicked()"),
                               self.onStart)
        QtCore.QObject.connect(self.ui.stopBtn,
                               QtCore.SIGNAL("clicked()"),
                               self.onStop)
        QtCore.QObject.connect(self.ui.updateKnob,
                               QtCore.SIGNAL('valueChanged(int)'),
                               self.onRefreshRateChange)
        QtCore.QObject.connect(self.timer,
                               QtCore.SIGNAL('timeout()'),
                               self.onTimer)
Exemple #7
0
class gui:

    def __init__(self):
# declarações da interface gráfica
        print("Gerando a interface gráfica")

        self.app = QApplication(sys.argv)

# janela principal
        self.wMain = QMainWindow()
        self.ui = Main()
        self.ui.setupUi(self.wMain)

# janela ata
        self.wAta = QMainWindow()
        self.uiAta = Ata()
        self.uiAta.setupUi(self.wAta)

# janela gerar ata
        self.wAtaGerar = QMainWindow()
        self.uiAtaGerar = AtaGerar()
        self.uiAtaGerar.setupUi(self.wAtaGerar)

# janela convocação
        self.wConvoc = QMainWindow()
        self.uiConvoc = Convoc()
        self.uiConvoc.setupUi(self.wConvoc)

# janela gerar convocação
        self.wConvocGerar = QMainWindow()
        self.uiConvocGerar = ConvocGerar()
        self.uiConvocGerar.setupUi(self.wConvocGerar)

# janela departamentos
        self.wDepartamentos = QMainWindow()
        self.uiDepartamentos = Departamentos()
        self.uiDepartamentos.setupUi(self.wDepartamentos)
        
# seta a mesma folha de estilos e bloqueio para todas as janelas

        for janela in [
            self.wMain,
            self.wAta,
            self.wAtaGerar,
            self.wConvoc,
            self.wConvocGerar,
            self.wDepartamentos
        ]:
            janela.setWindowModality(Qt.ApplicationModal)       

# inicializa a janela
        self.wMain.show()
Exemple #8
0
    def __init__(self):
        QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        self.stock_window = None
        self.order_window = None
        self.custom_window = None
        self.office_ext_window = None

        self.stockBtn.clicked.connect(self.stock_btn_on_click)
        self.orderBtn.clicked.connect(self.order_btn_on_click)
        self.customBtn.clicked.connect(self.custom_btn_on_click)
        self.officeExpBtn.clicked.connect(self.office_exp_btn_on_click)
class OpcDataTrender(QtGui.QMainWindow):
    def __init__(self):
        super(OpcDataTrender, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.aboutDialog = MyAboutDialog(self)

        self.samples = []

        try:
            self.opc = OPCHandler()
        except OpenOPC.OPCError, error_msg:
            self.opc = None
            QtGui.QMessageBox.question(
                self.ui.centralwidget, u"OPC Error",
                u"Failed to open a connection to OPC server :\n%s" % error_msg,
                QtGui.QMessageBox.Ok)
            exit()

        self.timer = QtCore.QTimer()
        self.startTimestamp = 0

        ###########
        # Threads #
        ###########
        # OPC reading thread
        self.opcThread = OPCReadingThread()
        self.opcThread.dataReady.connect(self.getData,
                                         QtCore.Qt.QueuedConnection)

        QtCore.QObject.connect(self.ui.actionAddTag,
                               QtCore.SIGNAL("triggered()"), self.addTag)
        QtCore.QObject.connect(self.ui.actionAbout,
                               QtCore.SIGNAL("triggered()"),
                               self.aboutDialog.open)

        QtCore.QObject.connect(QtCore.QCoreApplication.instance(),
                               QtCore.SIGNAL("aboutToQuit()"), self.quit)

        QtCore.QObject.connect(self.ui.startBtn, QtCore.SIGNAL("clicked()"),
                               self.onStart)
        QtCore.QObject.connect(self.ui.stopBtn, QtCore.SIGNAL("clicked()"),
                               self.onStop)
        QtCore.QObject.connect(self.ui.updateKnob,
                               QtCore.SIGNAL('valueChanged(int)'),
                               self.onRefreshRateChange)
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL('timeout()'),
                               self.onTimer)
Exemple #10
0
 def __init__(self, parent=None):
     super(MainWindow, self).__init__(parent)
     self.mainwindow = Ui_MainWindow()
     self.mainwindow.setupUi(self)
     self.header_list = ['Subject', 'From', 'Date']
     self.ui_extra_setup()
     self.load_groups()
Exemple #11
0
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.userInfo = None
        self.setupUi(self)
        self.setWindowTitle("Waifu2x-Gui")
        self.msgForm = QtBubbleLabel(self)
        self.settingForm = QtSetting(self)
        self.settingForm.hide()
        self.settingForm.LoadSetting()

        self.aboutForm = QtAbout(self)
        self.img = QtImg()
        self.stackedWidget.addWidget(self.img)
        # self.resize(1000, 1000)
        self.menuabout.triggered.connect(self.OpenAbout)
        desktop = QGuiApplication.primaryScreen().geometry()
Exemple #12
0
    def __init__(self):
        # declarações da interface gráfica

        self.app = QApplication(sys.argv)

        # janela principal
        self.wMain = QMainWindow()
        self.ui = Main()
        self.ui.setupUi(self.wMain)

        self.wMain.setWindowIcon(QIcon("resources/icone.png"))

        self.wAdd = QDialog()
        self.uiAdd = Item()
        self.uiAdd.setupUi(self.wAdd)

        self.wEditar = QDialog()
        self.uiEditar = Item()
        self.uiEditar.setupUi(self.wEditar)

        self.wEntrada = QDialog()
        self.uiEntrada = Entrada()
        self.uiEntrada.setupUi(self.wEntrada)

        self.wPausa = QDialog()
        self.uiPausa = Pausa()
        self.uiPausa.setupUi(self.wPausa)

        self.wExcluir = QDialog()
        self.uiExcluir = Excluir()
        self.uiExcluir.setupUi(self.wExcluir)

        self.wHistorico = QDialog()
        self.uiHistorico = Historico()
        self.uiHistorico.setupUi(self.wHistorico)

        self.wFerias = QDialog()
        self.uiFerias = Ferias()
        self.uiFerias.setupUi(self.wFerias)

        self.wComparar = QDialog()
        self.uiComparar = Comparar()
        self.uiComparar.setupUi(self.wComparar)

        self.wPlanejar = QDialog()
        self.uiPlanejar = Planejar()
        self.uiPlanejar.setupUi(self.wPlanejar)
        self.uiPlanejar.stackedWidget.setCurrentIndex(0)

        for janela in [
                self.wMain, self.wAdd, self.wEditar, self.wEntrada,
                self.wExcluir, self.wHistorico, self.wFerias, self.wComparar,
                self.wPlanejar, self.wPausa
        ]:
            janela.setWindowModality(Qt.ApplicationModal)

# inicializa a janela
        self.wMain.show()
    def __init__(self):
        super(OpcDataTrender, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.aboutDialog = MyAboutDialog(self)

        self.samples = []

        try:
            self.opc = OPCHandler()
        except OpenOPC.OPCError, error_msg:
            self.opc = None
            QtGui.QMessageBox.question(
                self.ui.centralwidget, u"OPC Error",
                u"Failed to open a connection to OPC server :\n%s" % error_msg,
                QtGui.QMessageBox.Ok)
            exit()
Exemple #14
0
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        self.products = Products(os.path.join(get_data_dir(), "products.csv"))
        self.cart = Cart(self.products)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.buildButtonGroups()
        self.buildPages()

        self.connectAll()

        logging.setStatusbar(self.ui.statusBar)

        self.setPage(list(self.pages.keys())[1])
        self.setCategoryPage(0)
Exemple #15
0
    def __init__(self, parent=None):
        super(MainWindows, self).__init__(parent)
        self.Ui = Ui_MainWindow()
        self.Ui.setupUi(self)
        self.setWindowIcon(QtGui.QIcon('./logo.ico'))
        self.port_list = []
        self.load()
        self.threads = []
        #列表框点击切换
        self.Ui.port_file.activated[str].connect(self.change_port_file)
        #引入文件
        self.Ui.pushButton_file.clicked.connect(self.open_file)
        #开始扫描
        self.Ui.pushButton_start.clicked.connect(self.start_scanner)

        #设置漏洞扫描表格属性  列宽度
        # self.Ui.tableWidget_result.setColumnWidth(0, 55 )
        self.Ui.tableWidget_result.setColumnWidth(0, 211)
        self.Ui.tableWidget_result.setColumnWidth(1, 100)
        self.Ui.tableWidget_result.setColumnWidth(2, 300)
Exemple #16
0
    def setupGui(self):
        self.app = QApplication(sys.argv)
        self.loginWindow = QDialog()

        self.window = QMainWindow()
        self.window.setWindowIcon(QIcon("icons/Newspaper-Feed.ico"))
        self.mainWindow = Ui_MainWindow()
        self.mainWindow.setupUi(self.window)

        self.loginDialog = Ui_LoginDialog()
        self.loginDialog.setupUi(self.loginWindow)    
        self.setupPrinters()
        self.setupSettings()
Exemple #17
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.progress = 0
        self.collections = None
        self.workingDirectory = None
        self.workingFiles = None
        self.workingFileType = None  # Should be ( archive | dir )
        self.workingFileIndex = 0
        self.scene = QGraphicsScene()
        self.ui.progressBar.hide()
        self.ui.graphicsView = PhotoViewer(self)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.ui.graphicsView.sizePolicy().hasHeightForWidth())
        self.ui.graphicsView.setSizePolicy(sizePolicy)
        self.ui.graphicsView.setObjectName("graphicsView")
        self.ui.gridLayout.addWidget(self.ui.graphicsView, 1, 0, 1, 1)

        self.main()
    def __init__(self):
        super(OpcDataTrender, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.aboutDialog = MyAboutDialog(self)

        self.samples = []

        try:
            self.opc = OPCHandler()
        except OpenOPC.OPCError, error_msg:
            self.opc = None
            QtGui.QMessageBox.question(self.ui.centralwidget,
                                       u"OPC Error",
                                       u"Failed to open a connection to OPC server :\n%s" % error_msg,
                                       QtGui.QMessageBox.Ok)
            exit()
Exemple #19
0
 def login(self):
     login_url = "http://localhost:8080/api/login"
     username = self.lineEdit.text()
     password = self.lineEdit_2.text()
     data = {"username": username, "password": password}
     response = requests.post(login_url, data=data)
     if "{" in response.text and "}" in response.text:
         print("DSADS")
         self.json = response.json()
         if self.json["bad_credentials"]:
             print("bad_credentials")
         else:
             print("Logged in")
             with open("token", "w+") as file:
                 file.write(self.json["token"])
             self.close()
             Ui_MainWindow().login()
     else:
         print("Something unexpected happened")
    def __init__(self):
        super(HmiLogViewer, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.aboutDialog = MyAboutDialog(self)

        self.model = None
        self.parserConfig = {'headers': None,
                             'cols': None}
        self.projectId = ""

        # Menu entries actions
        QtCore.QObject.connect(self.ui.actionOpen,
                               QtCore.SIGNAL("triggered()"),
                               self.openFile)
        QtCore.QObject.connect(self.ui.actionAddFile,
                               QtCore.SIGNAL("triggered()"),
                               lambda: self.openFile(True))
        QtCore.QObject.connect(self.ui.actionClose,
                               QtCore.SIGNAL("triggered()"),
                               self.closeFile)
        QtCore.QObject.connect(self.ui.actionSaveAs,
                               QtCore.SIGNAL("triggered()"),
                               self.saveFile)
        QtCore.QObject.connect(self.ui.actionImportConfigFile,
                               QtCore.SIGNAL("triggered()"),
                               self.importConfigFile)
        QtCore.QObject.connect(self.ui.actionAbout,
                               QtCore.SIGNAL("triggered()"),
                               self.aboutDialog.open)
        # Tool buttons actions
        QtCore.QObject.connect(self.ui.toolBtnOpen,
                               QtCore.SIGNAL("clicked()"),
                               self.openFile)
        QtCore.QObject.connect(self.ui.toolBtnAppend,
                               QtCore.SIGNAL("clicked()"),
                               lambda: self.openFile(True))
        QtCore.QObject.connect(self.ui.toolBtnSave,
                               QtCore.SIGNAL("clicked()"),
                               self.saveFile)
 def __init__(self):
     QMainWindow.__init__(self)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.init_app()
     self.get_title("")
class MainWnd(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.init_app()
        self.get_title("")

    def get_title(self, msg):
        if len(msg) > 0:
            title = self.tr("Compress neuron network (%s)" % msg)
        else:
            title = self.tr("Compress neuron network")
        self.setWindowTitle(title)

    def init_app(self):
        self.src_image = None
        self.reset()
        self.connect(self.ui.actionOpen, SIGNAL("triggered()"), self.load_img)
        self.connect(self.ui.teachButton, SIGNAL("clicked()"), self.teach)
        self.connect(self.ui.mEdit, SIGNAL("textChanged(QString)"), self.rebuildP)
        self.connect(self.ui.nEdit, SIGNAL("textChanged(QString)"), self.rebuildP)

        self.connect(self.ui.pEdit, SIGNAL("textChanged(QString)"), self.rebuildZ)
        self.ui.mEdit.setText("5")
        self.ui.nEdit.setText("5")

    def rebuildP(self, val):
        n, m = self.ui.nEdit.text(), self.ui.nEdit.text()
        if len(n) > 0 and len(m) > 0:
            p = int(n) * 2
            self.ui.pEdit.setText(str(p))
        self.rebuildZ(val)

    def rebuildZ(self, val):
        if str(self.ui.nEdit.text()) != "":
            n = int(self.ui.nEdit.text())
        else:
            n = 0
        if str(self.ui.mEdit.text()) != "":
            m = int(self.ui.mEdit.text())
        else:
            m = 0
        if str(self.ui.pEdit.text()) != "":
            p = int(self.ui.pEdit.text())
        else:
            p = 0
        if self.src_image is not None:
            w, h = self.src_image.rect().width(), self.src_image.rect().height()
            N, L = n * m, (w * h / n * m) * 3

            Z = ((N + L) * p + 2) / float(N * L)
            self.ui.comprLevelEdit.setText("%2.4f" % Z)

    def reset(self):
        self.ui.debugEdit.setText("")
        self.ui.teachW1ProgressBar.setValue(0)
        self.ui.teachW2ProgressBar.setValue(0)

    def teach(self):
        self.reset()
        self.teach_process()

    def teach_handler(self, teach_info):
        layer = 1
        if layer == 0:
            self.ui.teachW1ProgressBar.setMaximum(teach_info["max_iters"])
            self.ui.teachW1ProgressBar.setValue(teach_info["iter"])
        elif layer == 1:
            self.ui.teachW2ProgressBar.setMaximum(teach_info["max_iters"])
            self.ui.teachW2ProgressBar.setValue(teach_info["iter"])
        self.debug(
            "Iteration: %d Error: %2.5f Alpha: %2.5f, Alpha': %2.5f"
            % (teach_info["c_iter"], teach_info["error"], teach_info["alpha"], teach_info["alpha_"])
        )

    def compr_handler(self, img):
        img.save("out.png")
        self.dest_label = QLabel()
        self.dest_image = QImage("out.png")
        to_size = self.ui.comprScrollArea.size()
        self.dest_image = self.dest_image.scaled(to_size, Qt.KeepAspectRatio)
        self.dest_label.setPixmap(QPixmap.fromImage(self.dest_image))
        self.ui.comprScrollArea.setWidget(self.dest_label)

    def debug(self, msg):
        self.ui.debugEdit.setText(msg + "\n" + self.ui.debugEdit.toPlainText())

    def teach_process(self):
        n = int(self.ui.nEdit.text())
        m = int(self.ui.mEdit.text())
        p = int(self.ui.pEdit.text())
        e_max = float(self.ui.errorSpinBox.value())
        alpha = float(self.ui.alphaSpinBox.value())

        max_iters = int(self.ui.maxIterationsSB.value())

        params = {
            "e_max": e_max,
            "n": n,
            "m": m,
            "p": p,
            "alpha": alpha,
            "alpha_": alpha,
            "out": "compressed.png",
            "img": str(self.srcFileName),
            "iters": max_iters,
        }

        if self.ui.adaptiveW1checkBox.checkState() == Qt.Checked:
            params["alpha"] = -1
        if self.ui.adaptiveW2checkBox.checkState() == Qt.Checked:
            params["alpha_"] = -1
        thread = CompressThread(self, params, self.teach_handler)
        self.connect(thread, SIGNAL("handle"), self.teach_handler)
        self.connect(thread, SIGNAL("compressed"), self.compr_handler)
        self.connect(thread, SIGNAL("debug"), self.debug)
        thread.start()

    def load_img(self):
        self.srcFileName = QFileDialog.getOpenFileName(self, self.tr("Open image"), QDir.currentPath())

        if self.srcFileName is not None:
            self.src_label = QLabel()
            self.src_image = QImage(self.srcFileName)
            to_size = self.ui.srcScrollArea.size()
            self.src_image = self.src_image.scaled(to_size, Qt.KeepAspectRatio)
            self.src_label.setPixmap(QPixmap.fromImage(self.src_image))
            self.ui.srcScrollArea.setWidget(self.src_label)
Exemple #23
0
class Main:    
    def main(self):
        self.reader = GoogleReader.reader.GoogleReader()
        self.setupGui()
        self.setupSignals()
        self.showGui()
        sys.exit(self.app.exec_())

    def setupGui(self):
        self.app = QApplication(sys.argv)
        self.loginWindow = QDialog()

        self.window = QMainWindow()
        self.window.setWindowIcon(QIcon("icons/Newspaper-Feed.ico"))
        self.mainWindow = Ui_MainWindow()
        self.mainWindow.setupUi(self.window)

        self.loginDialog = Ui_LoginDialog()
        self.loginDialog.setupUi(self.loginWindow)    
        self.setupPrinters()
        self.setupSettings()
        #self.loginWindow.setParent(self.window)

    def setupSettings(self):
        pass

    def setupPrinters(self):
        printers = QPrinterInfo.availablePrinters()
        self.printerModel = QStandardItemModel()
        count = 0
        for p in printers:
            item = QStandardItem(p.printerName())
            item._printer = p
            self.printerModel.appendRow(item)
            if (p.isDefault()):
                defaultIndex = count
        self.mainWindow.printerList.setModel(self.printerModel)
        self.mainWindow.printerList.setCurrentIndex(defaultIndex)
        
    def getSelectedPrinter(self):
        index = self.mainWindow.printerList.currentIndex()
        item = self.printerModel.item(index)
        printerInfo = item._printer
        printer = QPrinter(printerInfo)
        return printer
        
    def showGui(self):
        self.window.show()
        self.loginWindow.exec_()
        

    def slotLogin(self):
        username = self.loginDialog.emailAddress.text()
        password = self.loginDialog.password.text()
        self.reader.identify(username, password)
        if (self.reader.login()):
            self.loginWindow.accept()
            #self.getTags()
            self.getSubscriptions()
        else:
            self.loginDialog.errorLabel.setText("Login failed")

    def setupSignals(self):
        QObject.connect(self.loginDialog.loginButton, SIGNAL("clicked()"), self.slotLogin)
        QObject.connect(self.mainWindow.previewButton, SIGNAL("clicked()"), self.slotPreview)
        QObject.connect(self.mainWindow.printButton, SIGNAL("clicked()"), self.slotPrint)
    
    def slotPrint(self):
        self.createHtml()
        self.createPreview()
        self.webFrame.print_(self.getSelectedPrinter())
        if (self.mainWindow.markReadItems.isChecked()):
            self.markPrintedArticlesAsRead()
        
    
    def slotPreview(self):
        self.createHtml()
        self.createPreview()
        self.showPreview()


    def markPrintedArticlesAsRead(self):
        for entry in self.unread:
            print "Marking entry as read: %s" % entry
            self.reader.set_read(entry['google_id'])
        

    def getEntries(self):
        content = []
        sub_ids = self.getCheckedSubscriptions()
        maxArts = self.mainWindow.maxArticles.value()
        for i in sub_ids:
            feed = self.reader.get_feed(feed = i, exclude_target=CONST.ATOM_STATE_READ, count = maxArts)
            entries = feed.get_entries()
            while True:
                try:
                    entry = entries.next()
                    content.append(entry)
                except StopIteration:
                    break
        return content


    def createHtml(self):
        self.unread = []
        html = u"<html><head></head><body>"
        for entry in self.getEntries():
            html = html + u"<h1>%s</h1>" % entry["title"]
            html = html + u"<i>%s %s</i><br />" % (entry["author"], entry["link"])
            html = html + entry["content"]
            self.unread.append(entry)
        html = html + u"</body></html>"
        self.html = html


        
    def createPreview(self):
        self.webFrame = QWebView()
        self.webFrame.setHtml(self.html)
    
    def showPreview(self):        
        self.webFrame.show()

        
    def getSubscriptions(self):
        self.subModel = QStandardItemModel()
        subs = self.reader.get_subscription_list()['subscriptions']
        for s in subs:
            label = s['title']
            sub_id = s['id']
            item = QStandardItem(label)
            item.sub_id = sub_id
            item.setCheckable(True)
            self.subModel.appendRow(item)
        self.mainWindow.labelList.setModel(self.subModel)

    def getCheckedSubscriptions(self):
        subs = []
        for i in range(self.subModel.rowCount()):
            item = self.subModel.item(i)
            if (item.checkState() == Qt.Checked):
                subs.append(item.sub_id)
        return subs
Exemple #24
0
 def setupUi(self):
     Ui_MainWindow.setupUi(self, self)
     self.tableViewDataOutput.setModel(self.query_model)
     self.database_menu.get_database_layout(self.treeWidgetDatabaseLayout)
     self.toolBar.addWidget(self.database_menu.get_combo_box(self.toolBar))
     self.setupTextEditQuery()
Exemple #25
0
def replay_event(main, setReplay):
    def wrapped():
        setReplay(True)
        main.close()

    return wrapped


if __name__ == '__main__':
    replay = False
    running = False
    sock = socket(AF_INET, SOCK_DGRAM)

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    main = Ui_MainWindow()
    main.setupUi(MainWindow)

    buttons = {
        "a": main.button_a,
        "b": main.button_b,
        "c": main.button_c,
        "d": main.button_d,
        "e": main.button_e,
        "f": main.button_f,
        "g": main.button_g,
        "h": main.button_h
    }

    main.label.setText("Wait...")
class HmiLogViewer(QtGui.QMainWindow):
    def __init__(self):
        super(HmiLogViewer, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.aboutDialog = MyAboutDialog(self)

        self.model = None
        self.parserConfig = {'headers': None,
                             'cols': None}
        self.projectId = ""

        # Menu entries actions
        QtCore.QObject.connect(self.ui.actionOpen,
                               QtCore.SIGNAL("triggered()"),
                               self.openFile)
        QtCore.QObject.connect(self.ui.actionAddFile,
                               QtCore.SIGNAL("triggered()"),
                               lambda: self.openFile(True))
        QtCore.QObject.connect(self.ui.actionClose,
                               QtCore.SIGNAL("triggered()"),
                               self.closeFile)
        QtCore.QObject.connect(self.ui.actionSaveAs,
                               QtCore.SIGNAL("triggered()"),
                               self.saveFile)
        QtCore.QObject.connect(self.ui.actionImportConfigFile,
                               QtCore.SIGNAL("triggered()"),
                               self.importConfigFile)
        QtCore.QObject.connect(self.ui.actionAbout,
                               QtCore.SIGNAL("triggered()"),
                               self.aboutDialog.open)
        # Tool buttons actions
        QtCore.QObject.connect(self.ui.toolBtnOpen,
                               QtCore.SIGNAL("clicked()"),
                               self.openFile)
        QtCore.QObject.connect(self.ui.toolBtnAppend,
                               QtCore.SIGNAL("clicked()"),
                               lambda: self.openFile(True))
        QtCore.QObject.connect(self.ui.toolBtnSave,
                               QtCore.SIGNAL("clicked()"),
                               self.saveFile)

    def getItemParserConfig(self, projectId=""):
        """

        :param projectId: str
        :return: dict
        """
        projectId = projectId.strip()
        try:
            # First open the config file which is in the same directory than the executable
            with open("HmiLogViewer.yaml", "r") as f:
                return self.parseConfig(f, projectId)
        except (IOError, OSError):
            try:
                with open(os.path.join(self.getConfigPath(), "HmiLogViewer.yaml"), "r") as f:
                    return self.parseConfig(f, projectId)
            except (IOError, OSError) as e:
                QtGui.QMessageBox.critical(self.ui.centralwidget,
                                           u"Config loading failed",
                                           u"Unable to read config file.\nReturned error is :\n%s" % e,
                                           QtGui.QMessageBox.Ok)
                return {'headers': {},
                        'cols': {'decimals': 0,
                                 'values': {},
                                 'color': {},
                                 'visible': True}}

    def parseConfig(self, fp, projectId):
        """
        Parse config file for the projectId
        :param fp: file object
        :param projectId: str
        :return: dict
        """
        data = yaml.safe_load(fp)
        for d in data['LogData']:
            if projectId == d['projectId']:
                headers = ['Date']
                cols = []
                for item in d['items']:
                    headers.append(u"{}\n({})".format(item['name'], item['unit'])
                                   if item['unit'] else
                                   u"{}".format(item['name']))

                    try:
                        decimals = item['decimals']
                    except KeyError:
                        decimals = 0

                    try:
                        values = ast.literal_eval(item['values'])
                    except (KeyError, ValueError, SyntaxError):
                        values = {}

                    try:
                        color = ast.literal_eval(item['color'])
                    except (KeyError, ValueError, SyntaxError):
                        color = {}

                    try:
                        visible = item['visible']
                    except KeyError:
                        visible = True

                    cols.append({'decimals': decimals,
                                 'values': values,
                                 'color': color,
                                 'visible': visible})
                return {'headers': headers,
                        'cols': cols}
        # Raise exception if project is not found
        raise ProjectIdError()

    def getConfigPath(self):
        dirname = os.path.join("EriVallon", "HmiLogViewer")
        if 'ALLUSERSPROFILE' in os.environ:
            try:
                from win32com.shell import shellcon, shell
                appdata_path = shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_APPDATA, 0, 0)
            except ImportError:
                appdata_path = os.environ['ALLUSERSPROFILE']
            return os.path.join(appdata_path, dirname)
        elif 'XDG_CONFIG_HOME' in os.environ:
            return os.path.join(os.environ['XDG_CONFIG_HOME'], dirname)
        else:
            return os.path.join(os.environ['HOME'], '.config', dirname)

    def importConfigFile(self):
        sFilePath = QtGui.QFileDialog.getOpenFileName(self.ui.centralwidget,
                                                      u"Choose a config file to import",
                                                      QtCore.QString(),
                                                      "YAML config file (*.yaml)")
        if os.path.isfile(sFilePath):
            r = QtGui.QMessageBox.warning(self.ui.centralwidget,
                                          u"Load config file",
                                          u"You are about to load a new config file located at : %s\n\n"
                                          u"Make sure you have selected a correct config file, "
                                          u"incorrect file may result in a non-functional application." % sFilePath,
                                          QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel,
                                          QtGui.QMessageBox.Cancel)
            if r == QtGui.QMessageBox.Ok:
                configPath = self.getConfigPath()
                if not os.path.exists(configPath):
                    os.makedirs(configPath)
                shutil.copy(sFilePath, os.path.join(configPath, "HmiLogViewer.yaml"))

    def openFile(self, append=False):
        """
        Open a csv file
        :param append: Do not close previous file if True
        """
        sFilePath = QtGui.QFileDialog.getOpenFileName(self.ui.centralwidget,
                                                      u"Choose a log file",
                                                      QtCore.QString(),
                                                      "CSV (*.csv)")
        if os.path.isfile(sFilePath):
            if not append:
                self.closeFile()
            self.parseLogFile(str(sFilePath))
            self.ui.actionClose.setEnabled(True)
            self.ui.actionAddFile.setEnabled(True)
            self.ui.toolBtnAppend.setEnabled(True)
            self.ui.actionSaveAs.setEnabled(True)
            self.ui.toolBtnSave.setEnabled(True)
            
    def closeFile(self):
        """
        Effacer les données des fichiers ouverts
        """
        self.model = None
        self.projectId = ""
        self.setModel()
        self.ui.actionSaveAs.setEnabled(False)
        self.ui.toolBtnSave.setEnabled(False)
        self.ui.actionAddFile.setEnabled(False)
        self.ui.toolBtnAppend.setEnabled(False)
        
    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.accept()
        else:
            event.ignore()
    
    def dropEvent(self, event):
        for url in event.mimeData().urls():
            path = url.toLocalFile().toLocal8Bit().data()
            if os.path.isfile(path):
                self.parseLogFile(path)
                self.ui.actionClose.setEnabled(True)
                self.ui.actionAddFile.setEnabled(True)
                self.ui.toolBtnAppend.setEnabled(True)
                self.ui.actionSaveAs.setEnabled(True)
                self.ui.toolBtnSave.setEnabled(True)

    def setModel(self):
        self.model = LogReaderTableModel(self.parserConfig['headers'], self.ui.centralwidget)
        self.ui.tableView.setModel(self.model)
        
    def parseLogFile(self, filename):
        """
        Le fichier de journalisation est composé de 3 champs séparés par des tabulations :
        1 : Date au format jj/mm/aaaa
        2 : Heure au format HH:MM:SS
        3 : Le message composé de N champs séparés par des points virgules

            :param filename: file to be parsed
        """

        if not self.ui.tableView.model():
            self.setModel()

        try:
            with codecs.open(filename, "r", "utf-16") as f:
                for lineIdx, line in enumerate(f):
                    if line.endswith("\r\n"):
                        line = line[:-2]
                    if line.endswith("\n"):
                        line = line[:-1]

                    # Check for projectId value
                    if lineIdx == 0:
                        if self.projectId == "":
                            self.projectId = line
                            try:
                                self.parserConfig = self.getItemParserConfig(self.projectId)
                            except ProjectIdError:
                                QtGui.QMessageBox.warning(self.ui.centralwidget,
                                                          u"Config cannot be found",
                                                          u"A proper config cannot be found for this file",
                                                          QtGui.QMessageBox.Ok)
                                break
                            self.setModel()
                        elif line != self.projectId:
                            QtGui.QMessageBox.warning(self.ui.centralwidget,
                                                      u"Wrong log file",
                                                      u"The log file you are trying to open seems to be from "
                                                      u"a different project than the last opened file.\n"
                                                      u"Please close it before opening another.",
                                                      QtGui.QMessageBox.Ok)
                            break

                    lineFields = line.split()
                    # Check if lineField has correct field number : 1: Date / 2: Time / 3: Message
                    if len(lineFields) == 3:
                        # Le message est composé de N champs séparés par des points-virgule
                        # -> on les extrait et contrôle que le nombre de champs est correct par rapport au header
                        msgFields = lineFields[2].strip(";").split(";")
                        if len(msgFields) == len(self.parserConfig['headers']) - 1:
                            items = []
                            for field, fieldConfig in zip(msgFields, self.parserConfig['cols']):
                                decimals = fieldConfig['decimals']
                                values = fieldConfig['values']
                                color = fieldConfig['color']
                                visible = fieldConfig['visible']

                                try:
                                    evalField = ast.literal_eval(field)
                                except ValueError:
                                    evalField = field

                                try:
                                    if decimals != 0:
                                        item = QtGui.QStandardItem((unicode(float(field)/10.0**decimals)))
                                    else:
                                        item = QtGui.QStandardItem(unicode(values[evalField]))
                                except (ValueError, KeyError):
                                    item = QtGui.QStandardItem(unicode(field))

                                try:
                                    item.setData(QtGui.QColor(color[evalField]), COLOR_ROLE)
                                except (ValueError, KeyError):
                                    pass

                                items.append(item)
                            # Add date and time values on the top of the list
                            items.insert(0, QtGui.QStandardItem(" ".join(lineFields[:-1])))
                            # Add extra row for aesthetic reasons
                            items.append(QtGui.QStandardItem())

                            self.model.appendRow(items)
        except (IOError, OSError, UnicodeError) as e:
            QtGui.QMessageBox.critical(self.ui.centralwidget,
                                       u"Opening failed",
                                       u"Failed to open file.\nReturned error is :\n%s" % e,
                                       QtGui.QMessageBox.Ok)
        self.updateModel()
            
    def updateModel(self):        
        tv = self.ui.tableView
        tv.setModel(self.model)
        # Hide the last column to not resize it
        tv.setColumnHidden(self.model.columnCount(), True)
        # Resize cells to contents
        tv.resizeColumnsToContents()
        tv.resizeRowsToContents()
        # Unhide the last column previously hidden
        tv.setColumnHidden(self.model.columnCount(), False)

    def saveFile(self):
        sFilePath = QtGui.QFileDialog.getSaveFileName(self.ui.centralwidget,
                                                      u"Choose a log file",
                                                      QtCore.QString(),
                                                      "CSV (*.csv)")
        if sFilePath:
            try:
                with open(str(sFilePath), "wb") as f:
                    writer = csv.writer(f, delimiter=";")
                    # Write headers
                    writer.writerow([s.encode("cp1255") for s in self.parserConfig['headers']])
                    for row in xrange(self.model.rowCount()):
                        itemRow = ["%s" % self.model.item(row, col).data(QtCore.Qt.DisplayRole).toString()
                                   if col == 0 else
                                   self.model.item(row, col).data(QtCore.Qt.DisplayRole).toInt()[0]
                                   if col < 4 else
                                   "%s" % self.model.item(row, col).data(QtCore.Qt.DisplayRole).toReal()[0]
                                   for col in xrange(self.model.columnCount())]
                        writer.writerow(itemRow)
            except (IOError, OSError, UnicodeError) as e:
                QtGui.QMessageBox.critical(self.ui.centralwidget,
                                           u"Saving failed",
                                           u"Failed to save file.\nReturned error is :\n%s" % e,
                                           QtGui.QMessageBox.Ok)
Exemple #27
0
    if text == 'True':
        ui_main.bt_start.setText('2.全部开始')
    else:
        ui_main.ed_log.append(text)


if __name__ == '__main__':

    dataPath = 'datas/set.pkl'
    # 自定义一个信号
    ms = log_sg = Myignals()
    # 绑定日志更新的信号
    ms.log_add.connect(log_add)
    #实例化抢购对象
    hw = PanicBuying()
    t = []  #线程容器
    driver = []  #浏览器容器
    start = False  #全局暂停和开始的开关
    close_all = False
    app = QApplication(sys.argv)
    window_main = QMainWindow()  # 主界面
    ui_main = Ui_MainWindow()  # 实例化
    ui_main.setupUi(window_main)  # 运行里面的代码
    init_window_main()  # 初始化和对接代码功能
    with open('datas\main.qss', 'r') as f:
        style = f.read()
    window_main.setStyleSheet(style)

    window_main.show()
    sys.exit(app.exec_())
class HmiLogViewer(QtGui.QMainWindow):
    def __init__(self):
        super(HmiLogViewer, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.aboutDialog = MyAboutDialog(self)

        self.model = None
        self.parserConfig = {'headers': None, 'cols': None}
        self.projectId = ""

        # Menu entries actions
        QtCore.QObject.connect(self.ui.actionOpen,
                               QtCore.SIGNAL("triggered()"), self.openFile)
        QtCore.QObject.connect(self.ui.actionAddFile,
                               QtCore.SIGNAL("triggered()"),
                               lambda: self.openFile(True))
        QtCore.QObject.connect(self.ui.actionClose,
                               QtCore.SIGNAL("triggered()"), self.closeFile)
        QtCore.QObject.connect(self.ui.actionSaveAs,
                               QtCore.SIGNAL("triggered()"), self.saveFile)
        QtCore.QObject.connect(self.ui.actionImportConfigFile,
                               QtCore.SIGNAL("triggered()"),
                               self.importConfigFile)
        QtCore.QObject.connect(self.ui.actionAbout,
                               QtCore.SIGNAL("triggered()"),
                               self.aboutDialog.open)
        # Tool buttons actions
        QtCore.QObject.connect(self.ui.toolBtnOpen, QtCore.SIGNAL("clicked()"),
                               self.openFile)
        QtCore.QObject.connect(self.ui.toolBtnAppend,
                               QtCore.SIGNAL("clicked()"),
                               lambda: self.openFile(True))
        QtCore.QObject.connect(self.ui.toolBtnSave, QtCore.SIGNAL("clicked()"),
                               self.saveFile)

    def getItemParserConfig(self, projectId=""):
        """

        :param projectId: str
        :return: dict
        """
        projectId = projectId.strip()
        try:
            # First open the config file which is in the same directory than the executable
            with open("HmiLogViewer.yaml", "r") as f:
                return self.parseConfig(f, projectId)
        except (IOError, OSError):
            try:
                with open(
                        os.path.join(self.getConfigPath(),
                                     "HmiLogViewer.yaml"), "r") as f:
                    return self.parseConfig(f, projectId)
            except (IOError, OSError) as e:
                QtGui.QMessageBox.critical(
                    self.ui.centralwidget, u"Config loading failed",
                    u"Unable to read config file.\nReturned error is :\n%s" %
                    e, QtGui.QMessageBox.Ok)
                return {
                    'headers': {},
                    'cols': {
                        'decimals': 0,
                        'values': {},
                        'color': {},
                        'visible': True
                    }
                }

    def parseConfig(self, fp, projectId):
        """
        Parse config file for the projectId
        :param fp: file object
        :param projectId: str
        :return: dict
        """
        data = yaml.safe_load(fp)
        for d in data['LogData']:
            if projectId == d['projectId']:
                headers = ['Date']
                cols = []
                for item in d['items']:
                    headers.append(
                        u"{}\n({})".format(item['name'], item['unit'])
                        if item['unit'] else u"{}".format(item['name']))

                    try:
                        decimals = item['decimals']
                    except KeyError:
                        decimals = 0

                    try:
                        values = ast.literal_eval(item['values'])
                    except (KeyError, ValueError, SyntaxError):
                        values = {}

                    try:
                        color = ast.literal_eval(item['color'])
                    except (KeyError, ValueError, SyntaxError):
                        color = {}

                    try:
                        visible = item['visible']
                    except KeyError:
                        visible = True

                    cols.append({
                        'decimals': decimals,
                        'values': values,
                        'color': color,
                        'visible': visible
                    })
                return {'headers': headers, 'cols': cols}
        # Raise exception if project is not found
        raise ProjectIdError()

    def getConfigPath(self):
        dirname = os.path.join("EriVallon", "HmiLogViewer")
        if 'ALLUSERSPROFILE' in os.environ:
            try:
                from win32com.shell import shellcon, shell
                appdata_path = shell.SHGetFolderPath(
                    0, shellcon.CSIDL_COMMON_APPDATA, 0, 0)
            except ImportError:
                appdata_path = os.environ['ALLUSERSPROFILE']
            return os.path.join(appdata_path, dirname)
        elif 'XDG_CONFIG_HOME' in os.environ:
            return os.path.join(os.environ['XDG_CONFIG_HOME'], dirname)
        else:
            return os.path.join(os.environ['HOME'], '.config', dirname)

    def importConfigFile(self):
        sFilePath = QtGui.QFileDialog.getOpenFileName(
            self.ui.centralwidget, u"Choose a config file to import",
            QtCore.QString(), "YAML config file (*.yaml)")
        if os.path.isfile(sFilePath):
            r = QtGui.QMessageBox.warning(
                self.ui.centralwidget, u"Load config file",
                u"You are about to load a new config file located at : %s\n\n"
                u"Make sure you have selected a correct config file, "
                u"incorrect file may result in a non-functional application." %
                sFilePath, QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel,
                QtGui.QMessageBox.Cancel)
            if r == QtGui.QMessageBox.Ok:
                configPath = self.getConfigPath()
                if not os.path.exists(configPath):
                    os.makedirs(configPath)
                shutil.copy(sFilePath,
                            os.path.join(configPath, "HmiLogViewer.yaml"))

    def openFile(self, append=False):
        """
        Open a csv file
        :param append: Do not close previous file if True
        """
        sFilePath = QtGui.QFileDialog.getOpenFileName(self.ui.centralwidget,
                                                      u"Choose a log file",
                                                      QtCore.QString(),
                                                      "CSV (*.csv)")
        if os.path.isfile(sFilePath):
            if not append:
                self.closeFile()
            self.parseLogFile(str(sFilePath))
            self.ui.actionClose.setEnabled(True)
            self.ui.actionAddFile.setEnabled(True)
            self.ui.toolBtnAppend.setEnabled(True)
            self.ui.actionSaveAs.setEnabled(True)
            self.ui.toolBtnSave.setEnabled(True)

    def closeFile(self):
        """
        Effacer les données des fichiers ouverts
        """
        self.model = None
        self.projectId = ""
        self.setModel()
        self.ui.actionSaveAs.setEnabled(False)
        self.ui.toolBtnSave.setEnabled(False)
        self.ui.actionAddFile.setEnabled(False)
        self.ui.toolBtnAppend.setEnabled(False)

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        for url in event.mimeData().urls():
            path = url.toLocalFile().toLocal8Bit().data()
            if os.path.isfile(path):
                self.parseLogFile(path)
                self.ui.actionClose.setEnabled(True)
                self.ui.actionAddFile.setEnabled(True)
                self.ui.toolBtnAppend.setEnabled(True)
                self.ui.actionSaveAs.setEnabled(True)
                self.ui.toolBtnSave.setEnabled(True)

    def setModel(self):
        self.model = LogReaderTableModel(self.parserConfig['headers'],
                                         self.ui.centralwidget)
        self.ui.tableView.setModel(self.model)

    def parseLogFile(self, filename):
        """
        Le fichier de journalisation est composé de 3 champs séparés par des tabulations :
        1 : Date au format jj/mm/aaaa
        2 : Heure au format HH:MM:SS
        3 : Le message composé de N champs séparés par des points virgules

            :param filename: file to be parsed
        """

        if not self.ui.tableView.model():
            self.setModel()

        try:
            with codecs.open(filename, "r", "utf-16") as f:
                for lineIdx, line in enumerate(f):
                    if line.endswith("\r\n"):
                        line = line[:-2]
                    if line.endswith("\n"):
                        line = line[:-1]

                    # Check for projectId value
                    if lineIdx == 0:
                        if self.projectId == "":
                            self.projectId = line
                            try:
                                self.parserConfig = self.getItemParserConfig(
                                    self.projectId)
                            except ProjectIdError:
                                QtGui.QMessageBox.warning(
                                    self.ui.centralwidget,
                                    u"Config cannot be found",
                                    u"A proper config cannot be found for this file",
                                    QtGui.QMessageBox.Ok)
                                break
                            self.setModel()
                        elif line != self.projectId:
                            QtGui.QMessageBox.warning(
                                self.ui.centralwidget, u"Wrong log file",
                                u"The log file you are trying to open seems to be from "
                                u"a different project than the last opened file.\n"
                                u"Please close it before opening another.",
                                QtGui.QMessageBox.Ok)
                            break

                    lineFields = line.split()
                    # Check if lineField has correct field number : 1: Date / 2: Time / 3: Message
                    if len(lineFields) == 3:
                        # Le message est composé de N champs séparés par des points-virgule
                        # -> on les extrait et contrôle que le nombre de champs est correct par rapport au header
                        msgFields = lineFields[2].strip(";").split(";")
                        if len(msgFields) == len(
                                self.parserConfig['headers']) - 1:
                            items = []
                            for field, fieldConfig in zip(
                                    msgFields, self.parserConfig['cols']):
                                decimals = fieldConfig['decimals']
                                values = fieldConfig['values']
                                color = fieldConfig['color']
                                visible = fieldConfig['visible']

                                try:
                                    evalField = ast.literal_eval(field)
                                except ValueError:
                                    evalField = field

                                try:
                                    if decimals != 0:
                                        item = QtGui.QStandardItem((unicode(
                                            float(field) / 10.0**decimals)))
                                    else:
                                        item = QtGui.QStandardItem(
                                            unicode(values[evalField]))
                                except (ValueError, KeyError):
                                    item = QtGui.QStandardItem(unicode(field))

                                try:
                                    item.setData(
                                        QtGui.QColor(color[evalField]),
                                        COLOR_ROLE)
                                except (ValueError, KeyError):
                                    pass

                                items.append(item)
                            # Add date and time values on the top of the list
                            items.insert(
                                0,
                                QtGui.QStandardItem(" ".join(lineFields[:-1])))
                            # Add extra row for aesthetic reasons
                            items.append(QtGui.QStandardItem())

                            self.model.appendRow(items)
        except (IOError, OSError, UnicodeError) as e:
            QtGui.QMessageBox.critical(
                self.ui.centralwidget, u"Opening failed",
                u"Failed to open file.\nReturned error is :\n%s" % e,
                QtGui.QMessageBox.Ok)
        self.updateModel()

    def updateModel(self):
        tv = self.ui.tableView
        tv.setModel(self.model)
        # Hide the last column to not resize it
        tv.setColumnHidden(self.model.columnCount(), True)
        # Resize cells to contents
        tv.resizeColumnsToContents()
        tv.resizeRowsToContents()
        # Unhide the last column previously hidden
        tv.setColumnHidden(self.model.columnCount(), False)

    def saveFile(self):
        sFilePath = QtGui.QFileDialog.getSaveFileName(self.ui.centralwidget,
                                                      u"Choose a log file",
                                                      QtCore.QString(),
                                                      "CSV (*.csv)")
        if sFilePath:
            try:
                with open(str(sFilePath), "wb") as f:
                    writer = csv.writer(f, delimiter=";")
                    # Write headers
                    writer.writerow([
                        s.encode("cp1255")
                        for s in self.parserConfig['headers']
                    ])
                    for row in xrange(self.model.rowCount()):
                        itemRow = [
                            "%s" % self.model.item(row, col).data(
                                QtCore.Qt.DisplayRole).toString()
                            if col == 0 else self.model.item(row, col).data(
                                QtCore.Qt.DisplayRole).toInt()[0] if col < 4
                            else "%s" % self.model.item(row, col).data(
                                QtCore.Qt.DisplayRole).toReal()[0]
                            for col in xrange(self.model.columnCount())
                        ]
                        writer.writerow(itemRow)
            except (IOError, OSError, UnicodeError) as e:
                QtGui.QMessageBox.critical(
                    self.ui.centralwidget, u"Saving failed",
                    u"Failed to save file.\nReturned error is :\n%s" % e,
                    QtGui.QMessageBox.Ok)
Exemple #29
0
class MainWindow(QtWidgets.QMainWindow):
    """MainWindow is the boilerplate for our gui"""
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.progress = 0
        self.collections = None
        self.workingDirectory = None
        self.workingFiles = None
        self.workingFileType = None  # Should be ( archive | dir )
        self.workingFileIndex = 0
        self.scene = QGraphicsScene()
        self.ui.progressBar.hide()
        self.ui.graphicsView = PhotoViewer(self)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.ui.graphicsView.sizePolicy().hasHeightForWidth())
        self.ui.graphicsView.setSizePolicy(sizePolicy)
        self.ui.graphicsView.setObjectName("graphicsView")
        self.ui.gridLayout.addWidget(self.ui.graphicsView, 1, 0, 1, 1)

        self.main()

    # def resize(self, event):
    #     print(event)
    # self.ui.graphicsView.scale(self.width(), self.height())

    def main(self):
        """main is responsible for setting up the gui"""
        self.buttons()
        self.setWindowIcon(QtGui.QIcon(':/images/assets/icons/36/icon.png'))
        self.show()

    def quit(self):
        """quit exits the application gracefully"""
        print('Komics exited properly.')
        sys.exit()

    def closeEvent(self, event):
        print("Komics exited with x button.")
        event.accept()
        sys.exit()

    def buttons(self):
        # Actions
        self.ui.actionQuit.triggered.connect(self.quit)
        self.ui.actionOpen.triggered.connect(self.openFile)
        self.ui.actionOpen_Directory.triggered.connect(self.openDirectory)
        self.ui.actionNext_Page.triggered.connect(self.loadNext)
        self.ui.actionPrevious_Page.triggered.connect(self.loadPrev)
        self.ui.actionEnd_of_Collection.triggered.connect(self.archiveEnd)
        self.ui.actionStart_of_Collection.triggered.connect(
            self.archiveBeggining)
        self.ui.actionClose_Collection.triggered.connect(self.closeCollection)
        self.ui.actionGoTo_Page.triggered.connect(self.pageGoTo)
        self.ui.actionPrevious_Collection.triggered.connect(
            self.archivePrevious)
        self.ui.actionNext_Collection.triggered.connect(self.archiveNext)
        self.ui.actionZoom_In.triggered.connect(
            self.ui.graphicsView.zoomInKeys)
        self.ui.actionZoom_Out.triggered.connect(
            self.ui.graphicsView.zoomOutKeys)
        self.ui.actionScroll_Forward.triggered.connect(self.scrollHalfScreen)
        self.ui.actionFull_Screen.triggered.connect(self.viewFullScreen)

        # Page Controls
        self.ui.btnArchivePrevious.clicked.connect(self.archivePrevious)
        self.ui.btnArchiveBeggining.clicked.connect(self.archiveBeggining)
        self.ui.btnPageBack.clicked.connect(self.loadPrev)
        self.ui.btnPageGoTo.clicked.connect(self.pageGoTo)
        self.ui.btnPageForward.clicked.connect(self.loadNext)
        self.ui.btnArchiveEnd.clicked.connect(self.archiveEnd)
        self.ui.btnArchiveNext.clicked.connect(self.archiveNext)

        # View controls
        self.ui.btnViewWidthFit.clicked.connect(self.viewWidthFit)
        self.ui.btnViewHeightFit.clicked.connect(self.viewHeightFit)
        self.ui.btnViewFitToSize.clicked.connect(self.viewFitToSize)
        self.ui.btnViewManualZoom.clicked.connect(self.viewManualZoom)

        # Layout controls
        self.ui.btnPageDoublePage.clicked.connect(self.layoutDoublePage)

    """Start Buttons"""

    def archiveEnd(self):
        if self.workingFiles:
            self.workingFileIndex = len(self.workingFiles) - 1
            self.loadImage(self.workingFiles[self.workingFileIndex])
        else:
            self.okayMessageBox("Please load a collection")

    def archiveBeggining(self):
        if self.workingFiles:
            self.workingFileIndex = 0
            self.loadImage(self.workingFiles[self.workingFileIndex])
        else:
            self.okayMessageBox("Please load a collection")

    def archiveNext(self):
        self.okayMessageBox('You pressed archive next')

    def archivePrevious(self):
        self.okayMessageBox('You pressed Previous Archive')

    def pageGoTo(self):
        self.okayMessageBox('You pressed page goto')

    def viewWidthFit(self):
        self.okayMessageBox('You pressed Width fit')

    def viewHeightFit(self):
        self.okayMessageBox('You pressed height fit')

    def viewFitToSize(self):
        self.okayMessageBox('You pressed fit to size')

    def viewManualZoom(self):
        self.okayMessageBox('You pressed manual zoom')

    def layoutDoublePage(self):
        self.okayMessageBox('You pressed double page')

    def closeCollection(self):
        self.workingFiles = None
        self.workingFileIndex = 0
        self.ui.graphicsView.setScene(None)
        self.rf = None

    """End Buttons"""
    """Start Actions"""

    def viewFullScreen(self):
        self.ui.graphicsView.showFullScreen()

    def showFullScreen(self):
        self.ui.centralWidget.hide()
        # self.ui.menuBar.hide()
        # self.ui.graphicsView.showFullScreen()

    """End Actions"""

    def showProgress(self):
        self.ui.progressBar.show()
        self.progress = 0
        while self.progress < 100:
            self.progress += 0.00001
            self.ui.progressBar.setValue(self.progress)
        self.ui.progressBar.hide()

    def okayMessageBox(self, message, title='Message'):
        """Mixin"""
        QtWidgets.QMessageBox.question(self, title, message,
                                       QtWidgets.QMessageBox.Ok)

    def scrollHalfScreen(self):
        end = self.ui.graphicsView.scrollHalf()
        if end:
            self.loadNext()

    def loadImage(self, image):
        self.scene.clear()
        if type(image) is str:
            pm = QtGui.QPixmap(image)
            # self.scene.addPixmap(pm)
            # self.ui.graphicsView.setScene(self.scene)
            self.ui.graphicsView.setPhoto(pm)
        elif type(image) is rarfile.Rar3Info:
            im_type = image.filename.split('.')[-1].strip().upper()
            bts = self.rf.read(image)
            pm = QtGui.QPixmap()
            pm.loadFromData(bts, im_type)
            self.ui.graphicsView.setPhoto(pm)
            # self.scene.addPixmap(pm)
            # self.ui.graphicsView.setScene(self.scene)
        else:
            self.okayMessageBox("Invalid image format")

    def loadPrev(self):
        if self.workingFiles:
            if self.workingFileIndex - 1 >= 0:
                self.workingFileIndex -= 1
                self.loadImage(self.workingFiles[self.workingFileIndex])
            else:
                self.workingFileIndex = 0
                self.okayMessageBox(
                    "You've reached the begining of the collection")
        else:
            self.okayMessageBox("Please open a file or archive.")

    def loadNext(self):
        if self.workingFiles:
            if self.workingFileIndex + 1 < len(self.workingFiles):
                self.workingFileIndex += 1
                self.loadImage(self.workingFiles[self.workingFileIndex])
            else:
                self.workingFileIndex = 0
                self.okayMessageBox("You've reached the end :(")
        else:
            self.okayMessageBox("Please open a file or archive.")

    def openDirectory(self):
        diag = QFileDialog()
        path = QFileDialog.getExistingDirectory(diag, "Select Directory")
        if path:
            if os.path.isdir(path):
                self.workingFileIndex = 0
                self.workingFiles = [
                    os.path.join(path, file) for file in os.listdir(path)
                    if IMAGE_REGEX.match(file)
                ]
            if not self.workingFiles:
                self.okayMessageBox('No valid files found in directory')
            else:
                self.loadImage(self.workingFiles[self.workingFileIndex])

    # types: JPEG GIF PNG CBZ CBR CBT CBA CB7
    def openFile(self):
        diag = QFileDialog()
        options = QFileDialog.options(diag)
        path, _ = QFileDialog.getOpenFileName(diag,
                                              "QFileDialog.getOpenFileName()",
                                              "",
                                              ';;'.join(FILE_TYPES),
                                              options=options)
        filename, file_ext = os.path.splitext(path)
        if path:
            if file_ext in '.jpg .gif .png':
                self.workingFileIndex = 0
                self.workingFiles = [
                    os.path.dirname(path) + '/' + file
                    for file in os.listdir(os.path.dirname(path))
                    if IMAGE_REGEX.match(file)
                ]
                for i, file in enumerate(self.workingFiles):
                    if file == path:
                        self.workingFileIndex = i
                        break

                if not self.workingFiles:
                    self.okayMessageBox('No valid files found in directory')
                else:
                    self.loadImage(self.workingFiles[self.workingFileIndex])
            elif file_ext == '.cbr':
                # Unrar and open as directory
                self.rf = rarfile.RarFile(path, mode='r')
                self.workingFiles = [
                    f for f in self.rf.infolist()
                    if IMAGE_REGEX.match(f.filename)
                ]
                self.loadImage(self.workingFiles[0])
            else:
                self.okayMessageBox("Please use a valid filetype")
Exemple #30
0
class Gui:
    def __init__(self):
        # declarações da interface gráfica

        self.app = QApplication(sys.argv)

        # janela principal
        self.wMain = QMainWindow()
        self.ui = Main()
        self.ui.setupUi(self.wMain)

        self.wMain.setWindowIcon(QIcon("resources/icone.png"))

        self.wAdd = QDialog()
        self.uiAdd = Item()
        self.uiAdd.setupUi(self.wAdd)

        self.wEditar = QDialog()
        self.uiEditar = Item()
        self.uiEditar.setupUi(self.wEditar)

        self.wEntrada = QDialog()
        self.uiEntrada = Entrada()
        self.uiEntrada.setupUi(self.wEntrada)

        self.wPausa = QDialog()
        self.uiPausa = Pausa()
        self.uiPausa.setupUi(self.wPausa)

        self.wExcluir = QDialog()
        self.uiExcluir = Excluir()
        self.uiExcluir.setupUi(self.wExcluir)

        self.wHistorico = QDialog()
        self.uiHistorico = Historico()
        self.uiHistorico.setupUi(self.wHistorico)

        self.wFerias = QDialog()
        self.uiFerias = Ferias()
        self.uiFerias.setupUi(self.wFerias)

        self.wComparar = QDialog()
        self.uiComparar = Comparar()
        self.uiComparar.setupUi(self.wComparar)

        self.wPlanejar = QDialog()
        self.uiPlanejar = Planejar()
        self.uiPlanejar.setupUi(self.wPlanejar)
        self.uiPlanejar.stackedWidget.setCurrentIndex(0)

        for janela in [
                self.wMain, self.wAdd, self.wEditar, self.wEntrada,
                self.wExcluir, self.wHistorico, self.wFerias, self.wComparar,
                self.wPlanejar, self.wPausa
        ]:
            janela.setWindowModality(Qt.ApplicationModal)

# inicializa a janela
        self.wMain.show()

    def ajusta(self):
        self.ui.tableWidget.resizeColumnsToContents()
        tamanho_total = self.ui.tableWidget.width()
        colunas = []
        tamanho_tabela = 0
        for i in range(self.ui.tableWidget.columnCount()):
            colunas.append(self.ui.tableWidget.columnWidth(i))
            tamanho_tabela += self.ui.tableWidget.columnWidth(i)
        sobra = tamanho_total - tamanho_tabela
        extra = int(sobra / len(colunas)) - 3
        for i in range(0, len(colunas)):
            colunas[i] += extra
            self.ui.tableWidget.setColumnWidth(i, colunas[i])
Exemple #31
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        self.products = Products(os.path.join(get_data_dir(), "products.csv"))
        self.cart = Cart(self.products)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.buildButtonGroups()
        self.buildPages()

        self.connectAll()

        logging.setStatusbar(self.ui.statusBar)

        self.setPage(list(self.pages.keys())[1])
        self.setCategoryPage(0)

    def buildButtonGroups(self):
        self.ui.numpadButtons = []
        for i in range(self.ui.npGrid.count()):
            obj = self.ui.npGrid.itemAt(i).widget()
            if obj.text().isdigit():
                self.ui.numpadButtons.append(obj)

        self.ui.productButtons = []
        for i in range(self.ui.leftProductButtons.count()):
            self.ui.productButtons.append(self.ui.leftProductButtons.itemAt(i).widget())
            self.ui.productButtons.append(self.ui.rightProductButtons.itemAt(i).widget())

        self.ui.categoryButtons = []
        for i in range(self.ui.categoryLayout.count()):
            obj = self.ui.categoryLayout.itemAt(i).widget()
            if isinstance(obj, QtGui.QPushButton):
                self.ui.categoryButtons.append(obj)

    def buildPages(self):
        self.pages = OrderedDict()
        self.category_pages = OrderedDict()

        self.pages[FUNCTIONS_NAME] = FUNCTIONS_PAGE

        categories = self.products.categories()
        for category in categories:
            products = self.products.category_dict()[category]
            num_pages = ceil(len(products) / len(self.ui.productButtons))
            for i in range(num_pages):
                p2add = range(len(self.ui.productButtons)*i, len(self.ui.productButtons)*(i+1))

                if num_pages == 1:
                    name = category.capitalize()
                else:
                    name = category.capitalize() + ' ' + str(i + 1)
                self.pages[name] = []
                for j in p2add:
                    try:
                        self.pages[name].append(products[j])
                    except IndexError:
                        pass

        num_category_pages = ceil(len(self.pages) / len (self.ui.categoryButtons))
        for i in range(num_category_pages):
            p2add = range(len(self.ui.categoryButtons)*i, len(self.ui.categoryButtons)*(i+1))
            self.category_pages[i] = []
            for j in p2add:
                try:
                    page_name = list(self.pages.keys())[j]
                    self.category_pages[i].append(page_name)
                except IndexError:
                    pass

    def connectAll(self):
        # menuBar
        self.ui.actionQuit.triggered.connect(self.close)
        self.ui.actionFullscreen.triggered.connect(self.showFullScreen)
        self.ui.actionWindowed.triggered.connect(self.showMaximized)
        self.ui.actionGame.triggered.connect(self.openWhack)

        self.ui.amountList.clicked.connect(self.selectSameLine)
        self.ui.productList.clicked.connect(self.selectSameLine)
        self.ui.priceList.clicked.connect(self.selectSameLine)

        # numpad
        for button in self.ui.numpadButtons:
            button.clicked.connect(self.numpadInput)
        self.ui.numpadClearButton.clicked.connect(self.numpadClear)
        self.ui.numpadBackspaceButton.clicked.connect(self.numpadBackspace)

        self.ui.payCashButton.clicked.connect(self.payCash)
        self.ui.payPinButton.clicked.connect(self.payPin)

        # categories
        for button in self.ui.categoryButtons:
            button.clicked.connect(self.switchCategory)
        self.ui.prevBtn.clicked.connect(self.prevCategory)
        self.ui.nextBtn.clicked.connect(self.nextCategory)

        # products
        for button in self.ui.productButtons:
            button.clicked.connect(self.addProduct)

    def openWhack(self):
        whack = WhackDialog(self)
        whack.show()

    def openRetour(self):
        retour = RetourDialog(self)
        retour.show()

    def selectSameLine(self, index):
        row = index.row()
        self.ui.amountList.setCurrentItem(self.ui.amountList.item(row))
        self.ui.productList.setCurrentItem(self.ui.productList.item(row))
        self.ui.priceList.setCurrentItem(self.ui.priceList.item(row))

    def numpadInput(self):
        input = self.sender().text()

        if self.ui.numpadLineEdit.text() == "" and input == "0":
            return

        self.ui.numpadLineEdit.insert(input)

    def numpadClear(self):
        self.ui.numpadLineEdit.clear()

    def numpadBackspace(self):
        self.ui.numpadLineEdit.backspace()

    def payCash(self):
        self.pay(Method.CASH)

    def payPin(self):
        self.pay(Method.PIN)

    def switchCategory(self):
        self.setPage(self.sender().text())

    def prevCategory(self):
        self.setCategoryPage(self.current_category_page - 1)

    def nextCategory(self):
        self.setCategoryPage(self.current_category_page + 1)

    def addProduct(self):
        name = self.sender().text()

        if self.current_page == FUNCTIONS_NAME:
            return self.callFunction(name)

        if self.cart.isCheckedOut():
            self.cart.clear()

        product = self.products.dict()[name]
        self.cart.add(self.getNumpad(), product)
        self.numpadClear()
        self.updateReceipt()

    def setPage(self, page_name):
        page = self.pages[page_name]
        self.current_page = page_name

        for i, button in enumerate(self.ui.productButtons):
            try:
                name = page[i].name if hasattr(page[i], 'name') else page[i]
                button.setText(name)
                button.setEnabled(True)
                button.setFlat(False)
            except IndexError:
                button.setText("")
                button.setEnabled(False)
                button.setFlat(True)

    def setCategoryPage(self, page_num):
        page = self.category_pages[page_num]
        self.current_category_page = page_num

        for i, button in enumerate(self.ui.categoryButtons):
            try:
                button.setText(page[i])
                button.setEnabled(True)
                button.setFlat(False)
            except IndexError:
                button.setText("")
                button.setEnabled(False)
                button.setFlat(True)

        if page_num < len(self.category_pages) - 1:
            self.ui.nextBtn.setEnabled(True)
        else:
            self.ui.nextBtn.setEnabled(False)

        if page_num > 0:
            self.ui.prevBtn.setEnabled(True)
        else:
            self.ui.prevBtn.setEnabled(False)

    def callFunction(self, function):
        if function == "Opmerking":
            self.comment()
        elif function == "Retour":
            self.pay(Method.CASH, retour=True)
        elif function == "EV":
            self.pay(Method.EV)
        elif function == "Retour EV":
            self.pay(Method.EV, retour=True)
        elif function == "Naborrel":
            self.pay(Method.NABORREL)
        elif function == "Retour naborrel":
            self.pay(Method.NABORREL, retour=True)
        elif function == "Regel verwijderen":
            self.removeLine()
        elif function == "Retour laatste":
            self.openRetour()

    def getNumpad(self):
        numpad = self.ui.numpadLineEdit.text()
        return 1 if numpad == "" else int(numpad)

    def removeLine(self):
        if self.cart.isCheckedOut():
            logger.warn("Deze transactie is al afgerekend")
            return

        item = self.ui.amountList.selectedItems()

        if not item:
            logger.warn("Geen regel geselecteerd")
            return

        row = self.ui.amountList.row(item[0])
        self.cart.contents.pop(row)
        self.updateReceipt()

    def comment(self):
        comment, ok = QtGui.QInputDialog.getText(self, "Opmerking", "Voer opmerking in")
        if ok and comment:
            self.cart.addCommentToFile(comment)

    def updateReceipt(self):
        self.ui.amountList.setStyleSheet(UNPROCESSED_STYLE)
        self.ui.productList.setStyleSheet(UNPROCESSED_STYLE)
        self.ui.priceList.setStyleSheet(UNPROCESSED_STYLE)
        self.ui.totalAmountLineEdit.setStyleSheet(UNPROCESSED_STYLE)
        self.ui.totalPriceLineEdit.setStyleSheet(UNPROCESSED_STYLE)

        self.ui.amountList.clear()
        self.ui.productList.clear()
        self.ui.priceList.clear()

        for entry in self.cart.contents:
            self.ui.amountList.addItem(str(entry[0]))
            self.ui.productList.addItem(entry[1])
            item = QtGui.QListWidgetItem(locale.currency(entry[2]))
            item.setTextAlignment(QtCore.Qt.AlignRight)
            self.ui.priceList.addItem(item)

        total = self.cart.total()
        self.ui.totalAmountLineEdit.setText(str(total[0]))
        self.ui.totalPriceLineEdit.setText(locale.currency(total[1]))

    def pay(self, method, retour=False):
        if self.cart.isCheckedOut():
            return logger.warn('Deze transactie is al afgerekend')

        if self.cart.isEmpty():
            return

        self.lastMethod = method

        if retour:
            self.cart.negate()
            self.updateReceipt()

        self.cart.checkOut(method)

        self.ui.amountList.setStyleSheet(PROCESSED_STYLE)
        self.ui.productList.setStyleSheet(PROCESSED_STYLE)
        self.ui.priceList.setStyleSheet(PROCESSED_STYLE)
        self.ui.totalAmountLineEdit.setStyleSheet(PROCESSED_STYLE)
        self.ui.totalPriceLineEdit.setStyleSheet(PROCESSED_STYLE)

        self.setPage(list(self.pages.keys())[1])
Exemple #32
0
class MainWindows(QtWidgets.QMainWindow, Ui_MainWindow):  #主窗口
    def __init__(self, parent=None):
        super(MainWindows, self).__init__(parent)
        self.Ui = Ui_MainWindow()
        self.Ui.setupUi(self)
        self.setWindowIcon(QtGui.QIcon('./logo.ico'))
        self.port_list = []
        self.load()
        self.threads = []
        #列表框点击切换
        self.Ui.port_file.activated[str].connect(self.change_port_file)
        #引入文件
        self.Ui.pushButton_file.clicked.connect(self.open_file)
        #开始扫描
        self.Ui.pushButton_start.clicked.connect(self.start_scanner)

        #设置漏洞扫描表格属性  列宽度
        # self.Ui.tableWidget_result.setColumnWidth(0, 55 )
        self.Ui.tableWidget_result.setColumnWidth(0, 211)
        self.Ui.tableWidget_result.setColumnWidth(1, 100)
        self.Ui.tableWidget_result.setColumnWidth(2, 300)

    def load(self):
        for file_dir, dirs_list, file_name_list in os.walk('dict'):
            for file_name in file_name_list:
                f = open('dict/' + file_name, 'r')
                port_Data = f.read().replace("\n", ",")
                f.close()
                self.port_list.append(file_name + ":" + port_Data)
                self.Ui.port_file.addItem(file_name.replace('.ini', ''))
        #设置初始数据
        set_Data_list = self.port_list[0].split('.ini:')
        self.Ui.textEdit_port.setText(set_Data_list[1])

    def change_port_file(self):
        com_name_text = self.Ui.port_file.currentText()
        for i in self.port_list:
            if com_name_text == i.split('.ini:')[0]:
                self.Ui.textEdit_port.setText(i.split('.ini:')[1])
                break

    def open_file(self):
        filename = self.file_open(r"Text Files (*.txt);;All files(*.*)")
        # with open(filename, 'r') as f:
        #     for line in f:
        #         self.ip_list.append(line.strip())
        # f.close()
        self.Ui.lineEdit_ip.setText(filename)

    def get_ip_f_list(self, file):
        all_list = []
        if os.path.exists(file):
            try:
                file = open(file, 'r', encoding='utf-8')
                for line in file:
                    all_list = all_list + self.get_ip_d_list(line)
                file.close()
                all_list2 = []
                for i in all_list:
                    if i not in all_list2:
                        all_list2.append(i)
                return list(filter(None, all_list2))  # 去除 none 和 空字符
            except:
                pass
                # printRed('Error:文件读取错误!')
        else:
            pass
            # printRed('Error:文件不存在')
    def get_ip_d_list(self, ip):
        ip_list = []
        if '/24' in ip:
            ip = ip.replace('/24', '')
            for i in range(1, 255):
                ip_list.append(ip[:ip.rfind('.')] + '.' + str(i))
        elif '-' in ip:
            ip_start = ip.split('.')[-1].split('-')[0]
            ip_end = ip.split('.')[-1].split('-')[1]
            if int(ip_start) > int(ip_end):
                numff = ip_start
                ip_start = ip_end
                ip_end = numff
            for i in range(int(ip_start), int(ip_end) + 1):
                ip_list.append(ip[:ip.rfind('.')] + '.' + str(i))
        else:
            ip_list = ip.split()
        # 列表去重
        all_list = []
        for i in ip_list:
            if i not in all_list:
                all_list.append(i)
        return list(filter(None, ip_list))  # 去除 none 和 空字符

    def start_scanner(self):
        input_Data = self.Ui.lineEdit_ip.text()
        try:
            if os.path.exists(input_Data):
                ip_list = self.get_ip_f_list(input_Data)
            else:
                ip_list = self.get_ip_d_list(input_Data)
        except:
            ip_list = self.get_ip_d_list(input_Data)
        port_list = self.Ui.textEdit_port.toPlainText().split(',')
        threadnum = self.Ui.lineEdit_thread.text()
        timeout = self.Ui.comboBox_timeout.currentText()
        self.scan(ip_list, port_list, threadnum, timeout)

    def scan(self, ip_list, port_list, threadNum, timeout):
        self.Ui.pushButton_start.setEnabled(False)
        portQueue = queue.Queue()  # 待检测端口队列,会在《Python常用操作》一文中更新用法
        for ip in ip_list:
            for i in port_list:
                portQueue.put(ip + ':' + str(i))
        self.createThread(threadNum, portQueue, timeout)
        # printYellow('[*] The Scan is Start')
        self.statusBar().showMessage("The Scan is Start", 5000)
        for t in self.threads:  # 启动线程
            t.setDaemon(True)  # 设置为后台线程,这里默认是False,设置为True之后则主线程不用等待子线程
            t.start()

        # for t in self.threads:  # 阻塞线程,等待线程结束
        #     t.join()
        # printYellow('[*] The Scan is complete!')

    def createThread(self, num, portQueue, timeout):
        self.threads = []
        for i in range(int(num)):
            i = threading.Thread(target=self.portScanner,
                                 args=(portQueue, timeout))
            self.threads.append(i)

    def portScanner(self, portQueue, timeout):
        while True:
            if portQueue.empty():  # 队列空就结束
                time.sleep(5)
                self.Ui.pushButton_start.setEnabled(True)
                return
            ip_port = portQueue.get()  # 从队列中取出
            host = ip_port.split(':')[0]
            port = ip_port.split(':')[1]
            # print(host,port)
            try:

                tcp = socket(AF_INET, SOCK_STREAM)
                tcp.settimeout(int(timeout))  # 如果设置太小,检测不精确,设置太大,检测太慢
                result = tcp.connect_ex(
                    (host, int(port)))  # 效率比connect高,成功时返回0,失败时返回错误码

                # print(222)
                try:
                    Banner = tcp.recv(1024).decode('utf-8').strip()
                except:
                    Banner = 'unknow'
                # print(Banner)
                if result == 0:
                    # print(host,port)
                    self.statusBar().showMessage(
                        host + ":" + port + " is open!", 5000)
                    row = self.Ui.tableWidget_result.rowCount()  # 获取行数
                    self.Ui.tableWidget_result.setRowCount(row + 1)
                    hostItem = QTableWidgetItem(host)
                    portItem = QTableWidgetItem(port)
                    BannerItem = QTableWidgetItem(Banner)
                    self.Ui.tableWidget_result.setItem(row, 0, hostItem)
                    self.Ui.tableWidget_result.setItem(row, 1, portItem)
                    self.Ui.tableWidget_result.setItem(row, 2, BannerItem)

            except:
                pass
                # exit()
            finally:
                tcp.close()

    # 文件打开对话框
    def file_open(self, type):
        fileName, selectedFilter = QFileDialog.getOpenFileName(
            self, (r"打开文件"), '', type)
        return (fileName)  # 返回文件路径

    # 保存文件对话框
    def file_save(self, filename):
        fileName, filetype = QFileDialog.getSaveFileName(
            self, (r"保存文件"), (r'C:\Users\Administrator\\' + filename),
            r"All files(*.*)")
        # print(fileName)
        return fileName
Exemple #33
0
class MainWindow(QMainWindow):
    
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.mainwindow = Ui_MainWindow()
        self.mainwindow.setupUi(self)
        self.header_list = ['Subject', 'From', 'Date']
        self.ui_extra_setup()
        self.load_groups()
        
        
    def ui_extra_setup(self):
        splitter_2 = self.mainwindow.splitter_2
        splitter_2.setSizes([30,200])    
        
        tv_groups = self.mainwindow.tv_groups
        groups_model = QStandardItemModel()
        groups_model.setHorizontalHeaderLabels(['Newsgroups'])
        tv_groups.setModel(groups_model)
        tv_groups.selectionModel().currentChanged.connect(self.group_selection_changed)
        tv_groups.setSelectionBehavior(QAbstractItemView.SelectRows)
        tv_groups.setIndentation(0)
        
        tv_headers = self.mainwindow.tv_headers
        headers_model = QStandardItemModel()
        headers_model.setHorizontalHeaderLabels(self.header_list)
        tv_headers.setModel(headers_model)
        tv_headers.selectionModel().currentChanged.connect(self.header_selection_changed)
        tv_headers.setSelectionBehavior(QAbstractItemView.SelectRows)
        tv_headers.setIndentation(0)
        
    def show_next_article(self):
        logging.debug('show_next_article')
        
        
    def clear_headers_table(self):
        tv_headers = self.mainwindow.tv_headers
        tv_headers.model().clear()
        tv_headers.model().setHorizontalHeaderLabels(self.header_list)
    
    
    def populate_threads(self, current):
        tv_headers = self.mainwindow.tv_headers
        self.clear_headers_table()
        currentItem = self.mainwindow.tv_groups.model().itemFromIndex(self.mainwindow.tv_groups.currentIndex())
        (reply, count, first, last, name) = nntp_conn.group(currentItem.newsgroup.name)
        
        (reply, subjects) = nntp_conn.xhdr('subject', str(int(last)-5) + '-' + last)
        
        for id, subject in subjects:
            d = {}
            try:
                reply, num, tid, list = nntp_conn.head(id)
            except NNTPTemporaryError:
                continue
                
            for line in list:
                for header in self.header_list:
                    if line[:len(header)] == header:
                        d[header] = line[len(header) + 2:]
            
            items = []
            it = QStandardItem()
            it.id = id
            it.setData(d['Subject'], Qt.DisplayRole)
            it.setCheckable(False)
            items.append(it)
            
            it = QStandardItem()
            it.id = id
            it.setData(d['From'], Qt.DisplayRole)
            items.append(it)
            
            it = QStandardItem()
            it.id = id
            it.setData(d['Date'], Qt.DisplayRole)
            items.append(it)
            
            tv_headers.model().appendRow(items)
    
    
    def group_selection_changed(self, current, previous):
        self.populate_threads(current)
    
    
    def populate_body(self, current):
        tb_body = self.mainwindow.tb_body
        tb_body.clear()
        tv_headers = self.mainwindow.tv_headers
        id = tv_headers.model().itemFromIndex(tv_headers.currentIndex()).id
        reply, num, tid, list = nntp_conn.body(id)
        body = "\n".join(list)    
        tb_body.setText(body)
            
    
    
    def header_selection_changed(self, current, previous):
        self.populate_body(current)
        

    def load_groups(self):
        groups = session.query(Newsgroup).filter_by(subscribed=True)
        tv = self.mainwindow.tv_groups
        
        for g in groups:
            items = []
            it = QStandardItem()
            it.newsgroup = g
            it.setData(g.name, Qt.DisplayRole)
            it.setCheckable(False)
            items.append(it)
            tv.model().appendRow(items)
        
        tv.selectionModel().select(tv.model().index(0, 0), QItemSelectionModel.Select)
Exemple #34
0
 def setupUi(self):
     Ui_MainWindow.setupUi(self, self)
     self.tableViewDataOutput.setModel(self.query_model)
     self.database_menu.get_database_layout(self.treeWidgetDatabaseLayout)
     self.toolBar.addWidget(self.database_menu.get_combo_box(self.toolBar))
     self.setupTextEditQuery()
Exemple #35
0
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import QtWidgets
from PyQt5.QtCore import pyqtSignal
import requests
from ui.login import Ui_LoginWindow
from ui.main import Ui_MainWindow

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = QMainWindow()
    main_ui = Ui_MainWindow()
    main_ui.login()
    sys.exit(app.exec_())