Ejemplo n.º 1
0
    def setData(self, index, value, role=Qt.EditRole):
        document = self.document(index)
        newPath = value

        if newPath == document.filePath():
            return False

        if newPath == '/dev/null':
            try:
                os.remove(document.filePath())
            except (OSError, IOError) as ex:
                QMessageBox.critical(core.mainWindow(), 'Not this time', 'The OS thinks it needs the file')
                return False
            core.workspace().closeDocument(document)
        else:
            try:
                os.rename(document.filePath(), newPath)
            except (OSError, IOError) as ex:
                QMessageBox.critical(core.mainWindow(), 'Failed to rename file', str(ex))
                return False
            else:
                document.setFilePath(newPath)
                document.saveFile()
                self.dataChanged.emit(index, index)

        return True
Ejemplo n.º 2
0
    def showObjects(self):

        if not (self.contoursCb.isChecked() or self.showBBoxes.isChecked()) or self._files is None:
            return

        index = self.slider.value()
        try:
            mp = TiffProcessor(
                self._files[index], self._regex, self.segdlg.segmentationParams(), self.cbar.checkedChannels()
            )

            # first channel for primary segementation
            mp.segmentation()
        except Exception as e:
            QMessageBox.critical(self, "Error", "%s:%s" % (type(e), str(e)))
        finally:
            objects = mp.objects()
            if not objects:
                self.viewer.clearPolygons()
                self.viewer.clearRects()
                return

            if self.contoursCb.isChecked():
                self.cbar.setContours(objects.contours)

            if self.showBBoxes.isChecked():
                self.cbar.drawRectangles(objects.centers.values(), self.segdlg.galSize.value(), isize=mp.size)
Ejemplo n.º 3
0
    def loadFromFile(self):
        fileName, _ = QFileDialog.getOpenFileName(self, "Open Address Book",
                '', "Address Book (*.abk);;All Files (*)")

        if not fileName:
            return

        try:
            in_file = open(str(fileName), 'rb')
        except IOError:
            QMessageBox.information(self, "Unable to open file",
                    "There was an error opening \"%s\"" % fileName)
            return

        self.contacts = pickle.load(in_file)
        in_file.close()

        if len(self.contacts) == 0:
            QMessageBox.information(self, "No contacts in file",
                    "The file you are attempting to open contains no "
                    "contacts.")
        else:
            for name, address in self.contacts:
                self.nameLine.setText(name)
                self.addressText.setText(address)

        self.updateInterface(self.NavigationMode)
Ejemplo n.º 4
0
    def add_url(self,):
        """
        add url(s) to the upload list.
        using a text box.
        """
        url_input = UrlInput()
        code = url_input.exec_()
        urls = url_input.text()

        new_entrys = []
        not_added = []

        if code and urls != '':
            for url in urls.split('\n'):
                # skip empty lines
                if url == '':
                    continue
                parsed_url = urlparse(url, scheme='http')
                scheme = parsed_url.scheme.lower()
                if scheme in ['http', 'https', 'ftp']:
                    new_entrys.append((urlunparse(parsed_url), 'url'))

                else:
                    not_added.append(url)

            if not_added:
                message = QMessageBox(QMessageBox.Warning, 'Fehler',
                                      ('Ein oder mehrere link(s) konnten '
                                       'nicht hinzugefügt werden.'),
                                      buttons=QMessageBox.Ok,
                                      parent=self)
                message.setDetailedText('\n'.join(not_added))

            self.list_view_files_model.add_files(new_entrys)
Ejemplo n.º 5
0
    def onOpenImageDir(self):
        self.cbar.clearContours()
        self.viewer.clearRects()
        self.viewer.clearPolygons()

        idir = self.imageDir.text()
        ofile = self.dataFile.text()
        if isdir(idir):
            path = dirname(idir)
        elif isfile(ofile):
            path = dirname(ofile)
        else:
            path = expanduser("~")

        # TODO use getOpenFileNames instead
        idir = QFileDialog.getExistingDirectory(self, "Select an image directory", path)
        # cancel button
        if not idir:
            return

        self.imageDir.setText(idir)

        scanner = FileScanner(self.structType.currentText(), idir)
        self._files = scanner()

        if not self._files:
            QMessageBox.warning(self, "Error", "No files found")
            return

        try:
            self._dimUpdate(self._files[0].file)
            self._initialImage()
        except IOError as e:
            pass
Ejemplo n.º 6
0
    def get_control_image_path(self, test_name):
        if os.path.isfile(test_name):
            return path

        # else try and find matching test image
        script_folder = os.path.dirname(os.path.realpath(sys.argv[0]))
        control_images_folder = os.path.join(
            script_folder, '../tests/testdata/control_images')

        matching_control_images = [x[0]
                                   for x in os.walk(control_images_folder) if test_name in x[0]]
        if len(matching_control_images) > 1:
            QMessageBox.warning(
                self, 'Result', 'Found multiple matching control images for {}'.format(test_name))
            return None
        elif len(matching_control_images) == 0:
            QMessageBox.warning(
                self, 'Result', 'No matching control images found for {}'.format(test_name))
            return None

        found_control_image_path = matching_control_images[0]

        # check for a single matching expected image
        images = glob.glob(os.path.join(found_control_image_path, '*.png'))
        filtered_images = [i for i in images if not i[-9:] == '_mask.png']
        if len(filtered_images) > 1:
            error(
                'Found multiple matching control images for {}'.format(test_name))
        elif len(filtered_images) == 0:
            error('No matching control images found for {}'.format(test_name))

        found_image = filtered_images[0]
        print('Found matching control image: {}'.format(found_image))
        return found_image
Ejemplo n.º 7
0
 def __init__(self, parent=None):
     """Init class."""
     super(Downloader, self).__init__(parent)
     self.setWindowTitle(__doc__)
     if not os.path.isfile(__file__) or not __source__:
         return
     if not os.access(__file__, os.W_OK):
         error_msg = ("Destination file permission denied (not Writable)! "
                      "Try again to Update but as root or administrator.")
         log.critical(error_msg)
         QMessageBox.warning(self, __doc__.title(), error_msg)
         return
     self._time, self._date = time.time(), datetime.now().isoformat()[:-7]
     self._url, self._dst = __source__, __file__
     log.debug("Downloading from {} to {}.".format(self._url, self._dst))
     if not self._url.lower().startswith("https:"):
         log.warning("Unsecure Download over plain text without SSL.")
     self.template = """<h3>Downloading</h3><hr><table>
     <tr><td><b>From:</b></td>      <td>{}</td>
     <tr><td><b>To:  </b></td>      <td>{}</td> <tr>
     <tr><td><b>Started:</b></td>   <td>{}</td>
     <tr><td><b>Actual:</b></td>    <td>{}</td> <tr>
     <tr><td><b>Elapsed:</b></td>   <td>{}</td>
     <tr><td><b>Remaining:</b></td> <td>{}</td> <tr>
     <tr><td><b>Received:</b></td>  <td>{} MegaBytes</td>
     <tr><td><b>Total:</b></td>     <td>{} MegaBytes</td> <tr>
     <tr><td><b>Speed:</b></td>     <td>{}</td>
     <tr><td><b>Percent:</b></td>     <td>{}%</td></table><hr>"""
     self.manager = QNetworkAccessManager(self)
     self.manager.finished.connect(self.save_downloaded_data)
     self.manager.sslErrors.connect(self.download_failed)
     self.progreso = self.manager.get(QNetworkRequest(QUrl(self._url)))
     self.progreso.downloadProgress.connect(self.update_download_progress)
     self.show()
     self.exec_()
Ejemplo n.º 8
0
def changeLanguage(cursor, language):
    """Changes the language of the pitch names."""
    c = lydocument.cursor(cursor, select_all=True)
    try:
        with qutil.busyCursor():
            changed = ly.pitch.translate.translate(c, language)
    except ly.pitch.PitchNameNotAvailable:
        QMessageBox.critical(None, app.caption(_("Pitch Name Language")), _(
            "Can't perform the requested translation.\n\n"
            "The music contains quarter-tone alterations, but "
            "those are not available in the pitch language \"{name}\"."
            ).format(name=language))
        return
    if changed:
        return
    if not cursor.hasSelection():
        # there was no selection and no language command, so insert one
        version = (documentinfo.docinfo(cursor.document()).version()
                   or lilypondinfo.preferred().version())
        ly.pitch.translate.insert_language(c.document, language, version)
        return
    # there was a selection but no command, user must insert manually.
    QMessageBox.information(None, app.caption(_("Pitch Name Language")),
        '<p>{0}</p>'
        '<p><code>\\include "{1}.ly"</code> {2}</p>'
        '<p><code>\\language "{1}"</code> {3}</p>'.format(
            _("The pitch language of the selected text has been "
                "updated, but you need to manually add the following "
                "command to your document:"),
            language,
            _("(for LilyPond below 2.14), or"),
            _("(for LilyPond 2.14 and higher.)")))
Ejemplo n.º 9
0
    def openVideo(self, filepath, duplicate_mode):
        movie = os.path.expanduser(filepath)
        if 'http://' not in filepath:
            if not os.access(movie, os.R_OK):
                print(('Error: %s file is not readable' % movie))
            sys.exit(1)

        split = urllib.parse.urlsplit(filepath)
        #name = QInputDialog.getText(self, 'Escolha nome do arquivo', 'Nome do arquivo:')
        name = split.path.split("/")[-1]
        #pa = os.path.join(res, name)
        if duplicate_mode:
            try:
                #media = instance.media_new(movie, 'sout=#duplicate{dst=file{dst=%s},dst=display}' % pa)
                pass
            except NameError:
                print(('NameError: % (%s vs Libvlc %s)' % (sys.exc_info()[1],
                                                           vlc.__version__, vlc.libvlc_get_version())))
        else:
            try:
                #media = instance.media_new(movie)
                if sys.platform in 'win32':
                    subprocess.Popen([os.path.join('vlc','vlc'), movie])
                else:
                    subprocess.Popen(['vlc', movie])
            except NameError:
                print(('NameError: % (%s vs Libvlc %s)' % (sys.exc_info()[1],
                                                           vlc.__version__, vlc.libvlc_get_version())))
                QMessageBox.critical(self, 'Erro','problema ao iniciar o vlc')
Ejemplo n.º 10
0
def get_fatal_crash_dialog(debug, data):
    """Get a fatal crash dialog based on a crash log.

    If the crash is a segfault in qt_mainloop and we're on an old Qt version
    this is a simple error dialog which lets the user know they should upgrade
    if possible.

    If it's anything else, it's a normal FatalCrashDialog with the possibility
    to report the crash.

    Args:
        debug: Whether the debug flag (--debug) was given.
        data: The crash log data.
    """
    ignored_frames = ['qt_mainloop', 'paintEvent']
    errtype, frame = parse_fatal_stacktrace(data)

    if (errtype == 'Segmentation fault' and
            frame in ignored_frames and
            objects.backend == usertypes.Backend.QtWebKit):
        title = "qutebrowser was restarted after a fatal crash!"
        text = ("<b>qutebrowser was restarted after a fatal crash!</b><br/>"
                "Unfortunately, this crash occurred in Qt (the library "
                "qutebrowser uses), and QtWebKit (the current backend) is not "
                "maintained anymore.<br/><br/>Since I can't do much about "
                "those crashes I disabled the crash reporter for this case, "
                "but this will likely be resolved in the future with the new "
                "QtWebEngine backend.")
        box = QMessageBox(QMessageBox.Critical, title, text, QMessageBox.Ok)
        box.setAttribute(Qt.WA_DeleteOnClose)
        return box
    else:
        return FatalCrashDialog(debug, data)
Ejemplo n.º 11
0
    def set_table_info(self):
        self.table_widget.setSortingEnabled(False)
        self.table_items = my_sql.sql_select(self.query_table_select)
        if "mysql.connector.errors" in str(type(self.table_items)):
                QMessageBox.critical(self, "Ошибка sql получение таблицы", self.table_items.msg, QMessageBox.Ok)
                return False

        self.table_widget.clearContents()
        self.table_widget.setRowCount(0)

        if not self.table_items:
            return False

        for table_typle in self.table_items:
            self.table_widget.insertRow(self.table_widget.rowCount())
            for column in range(2, len(table_typle)):
                item = QTableWidgetItem(str(table_typle[column]))
                item.setData(5, table_typle[0])
                self.table_widget.setItem(self.table_widget.rowCount() - 1, column - 2, item)

        self.table_widget.setSortingEnabled(True)

        try:
            item = self.tree_widget.currentItem()
            if item.data(0, 5) >= 0:  # Проверка не выбрано ли показать все!
                self.ui_sorting(item)
        except:
            pass

        if self.select_item:
            self.open_id(self.select_item)
            self.select_item = None
Ejemplo n.º 12
0
    def sessionOpened(self):
        if self.networkSession is not None:
            config = self.networkSession.configuration()

            if config.type() == QNetworkConfiguration.UserChoice:
                id = self.networkSession.sessionProperty('UserChoiceConfiguration')
            else:
                id = config.identifier()

            settings = QSettings(QSettings.UserScope, 'QtProject')
            settings.beginGroup('QtNetwork')
            settings.setValue('DefaultNetworkConfiguration', id)
            settings.endGroup();

        self.tcpServer = QTcpServer(self)
        if not self.tcpServer.listen():
            QMessageBox.critical(self, "Fortune Server",
                    "Unable to start the server: %s." % self.tcpServer.errorString())
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        self.statusLabel.setText("The server is running on\n\nIP: %s\nport %d\n\n"
                "Run the Fortune Client example now." % (ipAddress, self.tcpServer.serverPort()))
Ejemplo n.º 13
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.py = Ui_MainWindow()
        self.py.setupUi(self)

        """ combobox"""
        self.py.buttonBox.button(QDialogButtonBox.Close).clicked.connect(lambda: self.close())
        self.py.buttonBox.button(QDialogButtonBox.Save).clicked.connect(self.docSave)

        """ клик на таблицу"""
        self.py.tableView.doubleClicked.connect(self.twoClick)

        """ кнопки действия с таблицей"""
        self.py.addPeople.clicked.connect(lambda: self.addPeople(False))
        self.py.editPeople.clicked.connect(lambda: self.addPeople(True))
        self.py.delPeople.clicked.connect(self.delPeople)
        self.py.upTable.clicked.connect(lambda: self.tableFill())

        """ работа с проектом"""
        self.py.newProject.clicked.connect(lambda: self.newProject(False))
        self.py.editProject.clicked.connect(lambda: self.newProject(True))
        self.py.saveProject.clicked.connect(self.saveProject)
        self.py.loadProject.clicked.connect(self.loadProject)
        self.py.deleteProject.clicked.connect(self.deleteProject)

        """ проверка связи при запуске"""
        if not(connDB()):
            QMessageBox.question(self, 'Cообщение', 'Проблемы с БД', QMessageBox.Yes)
        table = selectProject()
        if table is not None:
            for i in table:
                self.py.nameProject.addItem(i[1], i[0])
        self.tableFill()
Ejemplo n.º 14
0
    def tryActivate(self, payload):
        if not app.mainWin.page.urlMatch(constants.V3_PAGE):
            return  # not v3 page

        if not payload["userid"]:
            return  # not logged in

        userid, status, code, peerid = app.etmpy.getActivationStatus()

        if userid == 0:
            # unbound
            if status == -1:
                QMessageBox.warning(None, "Xware Desktop 警告", "ETM未启用,无法激活。需要启动ETM后,刷新页面。",
                                    QMessageBox.Ok, QMessageBox.Ok)
                return

            elif status == 0 and code:
                self.sigActivateDevice.emit(code)  # to activate
                return

        else:
            if status == 0 and code:
                # re-activate
                self.sigActivateDevice.emit(code)
                return

            elif userid != int(payload["userid"]):
                QMessageBox.warning(None, "Xware Desktop 警告", "登录的迅雷账户不是绑定的迅雷账户。",
                                    QMessageBox.Ok, QMessageBox.Ok)
                return

            elif peerid not in payload["peerids"]:
                logging.warning("Network is slow, there're no peerids when xdjs loaded.")

            self.sigNotifyPeerId.emit(peerid)
Ejemplo n.º 15
0
Archivo: main.py Proyecto: sergeqwe/vk
    def close_full_pic_view(self, e):
        """Закрываем просмотр большой картинки левым кликом мыши"""
        if e.buttons() == QtCore.Qt.LeftButton:
            if self.DEBUG:
                print('left button pressed')
            self.prev_mode = 0  # Флаг, что выходим из просмотра в preview
            self.clear_screen()  # Удаляем изображение
            self.check_buttons()
            self.draw_pic()
            self.statusbar.showMessage('Page: ' + str(self.current_page))

        #  Созраняем изображение при нажатии правой кнопки мыши
        if e.buttons() == QtCore.Qt.RightButton:

            path = self.pic_save_path + '/' + os.path.basename(self.photo_max[self.photo_max_id])
            print(path)
            self.image.save(path)

            if os.path.exists(path):
                self.statusbar.showMessage('File saved to: ' + path )
            else:
                self.statusbar.showMessage('File is not saved. Сheck the path settings!' )
                msgBox = QMessageBox(
                    QMessageBox.Critical,
                    'Error', 'File is not saved. Сheck the path settings!\n<File-Settings-Path>',
                    QMessageBox.NoButton)
                msgBox.exec_()
Ejemplo n.º 16
0
	def runExtensionCommand(self, command, filefilter, defaultext):
		of = ('%of' in command)
		html = ('%html' in command)
		if of:
			if defaultext and not filefilter:
				filefilter = '*'+defaultext
			fileName = QFileDialog.getSaveFileName(self,
				self.tr('Export document'), '', filefilter)[0]
			if not fileName:
				return
			if defaultext and not QFileInfo(fileName).suffix():
				fileName += defaultext
		basename = '.%s.retext-temp' % self.currentTab.getDocumentTitle(baseName=True)
		if html:
			tmpname = basename+'.html'
			self.saveHtml(tmpname)
		else:
			tmpname = basename + self.currentTab.getMarkupClass().default_extension
			self.currentTab.saveTextToFile(fileName=tmpname, addToWatcher=False)
		command = command.replace('%of', '"out'+defaultext+'"')
		command = command.replace('%html' if html else '%if', '"'+tmpname+'"')
		try:
			Popen(str(command), shell=True).wait()
		except Exception as error:
			errorstr = str(error)
			QMessageBox.warning(self, '', self.tr('Failed to execute the command:')
			+ '\n' + errorstr)
		QFile(tmpname).remove()
		if of:
			QFile('out'+defaultext).rename(fileName)
Ejemplo n.º 17
0
 def received_move(self):
     try:
         data = self.socket.recv(1024)
     except Exception as e:
         QMessageBox.about(None, "Connection closed", e)
     move = pickle.loads(data)
     self.data_received.emit(move[0], move[1], move[2], move[3])
Ejemplo n.º 18
0
 def display_error(self, socketError):
   self.startTimer.stop()
   if socketError == 'timeout':
     QMessageBox.information(self, 'VNA', 'Error: connection timeout.')
   else:
     QMessageBox.information(self, 'VNA', 'Error: %s.' % self.socket.errorString())
   self.stop()
Ejemplo n.º 19
0
    def ok_to_continue(self):
        """
        Check if everything is ok with imagetab to continue conversion.

        Check if:
        - ImageMagick is missing.
        - Either none or both size lineEdits are active at a time.

        Return True if all tests pass, else False.
        """
        width = self.widthQLE.text()
        height = self.heightQLE.text()

        if not self.parent.imagemagick:
            QMessageBox.warning(self, 'FF Multi Converter - ' + self.tr(
                'Error!'), self.tr('ImageMagick is not installed!'))
            return False
        if (width and not height) or (not width and height):
            QMessageBox.warning(self, 'FF Multi Converter - ' + self.tr(
                     'Error!'), self.tr('The size LineEdit may not be empty.'))
            if width and not height:
                self.heightQLE.setFocus()
            else:
                self.widthQLE.setFocus()
            return False
        return True
Ejemplo n.º 20
0
    def triggered(self):
        self.low_edge  = [self.from_1.value(), self.from_2.value(), self.from_3.value()]
        self.high_edge = [self.to_1.value(), self.to_2.value(), self.to_3.value()]
        self.step = [self.st_1.value(), self.st_2.value(), self.st_3.value()]
        if self.custom_struct:
            solver = SolveExpTh(self.params)
        else:
            solver = Solve(self.params)
        p = [[i for i in range(self.low_edge[j], self.high_edge[j]+1, self.step[j])] for j in range(len(self.step))]
        best_deg = determine_deg(solver, p[0], p[1], p[2])
        bd = best_deg[0]
        self.res_1.setValue(bd[0])
        self.res_2.setValue(bd[1])
        self.res_3.setValue(bd[2])

        msgbox = QMessageBox()

        msgbox.setText('Best degrees:'+bd.__str__()+'.')
        msgbox.setInformativeText("Do you want to copy degrees in main window?")
        msgbox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        msgbox.setDefaultButton(QMessageBox.Ok)
        ret = msgbox.exec_()
        if ret == QMessageBox.Ok:
            self.update_degrees.emit(bd[0],bd[1], bd[2])
            self.close()
        # result = QMessageBox.question(self, 'Long-time operation',
        #                               'Adjusting degrees lasts long. Do you want to perform it?',
        #                               QMessageBox.Ok | QMessageBox.No)
        # if result == QMessageBox.Ok:
        #     BruteForceWindow.launch(self)

        #self.update_degrees.emit(3,3,3)
        return
Ejemplo n.º 21
0
def excepthook(excType, excValue, tracebackobj):
    """
    stolen from ERIC IDE!
    Global function to catch unhandled exceptions.
    
    @param excType exception type
    @param excValue exception value
    @param tracebackobj traceback object
    """
    separator = '-' * 80
    logFile = "error.log"
    notice = \
        """An unhandled exception occurred. Please report the problem\n"""\
        """via email to <%s>.\n"""\
        """A log has been written to "%s".\n\nError information:\n""" % \
        ("*****@*****.**", os.getcwd())
    versionInfo="OptiSim Version:\t" + getattr(ui.mainwindow, "__version__")
    timeString = time.strftime("%Y-%m-%d, %H:%M:%S")
    
    tbinfofile = io.StringIO()
    traceback.print_tb(tracebackobj, None, tbinfofile)
    tbinfofile.seek(0)
    tbinfo = tbinfofile.read()
    errmsg = '%s: \n%s' % (str(excType), str(excValue))
    sections = [separator, timeString, versionInfo, separator, errmsg, separator, tbinfo]
    msg = '\n'.join(sections)
    try:
        f = open(logFile, "w")
        f.write(msg)
        f.close()
    except IOError:
        pass
    errorbox = QMessageBox()
    errorbox.setText(str(notice)+str(msg))
    errorbox.exec_()
Ejemplo n.º 22
0
 def onEditPoint(line_edit, max_deduction):
     point_deduction = int(line_edit.text())
     if point_deduction > max_deduction:
         error = QMessageBox(QMessageBox.Critical, 'Error',"The point deduction per error missing can't be greater than the maximum point deduction", QMessageBox.Ok, self)
         error.show()
     else:
         self.deduction_per_elem = point_deduction
Ejemplo n.º 23
0
    def ui_calc(self):
        query = """SELECT pack.Cut_Id, pack.Number, CONCAT(product_article.Article, ' (', product_article_size.Size, ') [', product_article_parametrs.Name, ']'),
                            clients.Name, pack.Date_Make
                          FROM pack LEFT JOIN clients ON pack.Client_Id = clients.Id
                            LEFT JOIN product_article_parametrs ON pack.Article_Parametr_Id = product_article_parametrs.Id
                            LEFT JOIN product_article_size ON product_article_parametrs.Product_Article_Size_Id = product_article_size.Id
                            LEFT JOIN product_article ON product_article_size.Article_Id = product_article.Id
                            WHERE pack.Date_Make >= %s AND pack.Date_Make <= %s"""

        sql_info = my_sql.sql_select(query, (self.de_date_from.date().toString(Qt.ISODate), self.de_date_to.date().toString(Qt.ISODate)))
        if "mysql.connector.errors" in str(type(sql_info)):
            QMessageBox.critical(self, "Ошибка sql получения принятых пачек", sql_info.msg, QMessageBox.Ok)
            return False

        self.tableWidget.clearContents()
        self.tableWidget.setRowCount(0)

        if not sql_info:
            return False

        for table_typle in sql_info:
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            for column in range(len(table_typle)):
                if isinstance(table_typle[column], datetime.date):
                    text = table_typle[column].strftime("%d.%m.%Y")
                else:
                    text = str(table_typle[column])
                item = QTableWidgetItem(text)
                item.setData(5, table_typle[0])
                self.tableWidget.setItem(self.tableWidget.rowCount() - 1, column , item)
Ejemplo n.º 24
0
 def finishedLaunching(self):
     if sys.getfilesystemencoding() == 'ascii':
         # No need to localize this, it's a debugging message.
         msg = "Something is wrong with the way your system locale is set. If the files you're "\
            "scanning have accented letters, you'll probably get a crash. It is advised that "\
            "you set your system locale properly."
         QMessageBox.warning(self.directories_dialog, "Wrong Locale", msg)
Ejemplo n.º 25
0
    def render_color_gradient(self):
        num_leds = self.box_num_led.value()
        if num_leds < 2:
            QMessageBox.warning(get_main_window(), 'Color gradient',
                                'Can not render color gradient: There is only one LED configured.',
                                QMessageBox.Ok)
            return
        brightness = self.brightness_slider.value() * 8
        chip_type, num_channels = self.chip_type_combobox.itemData(self.chip_type_combobox.currentIndex())

        self.gradient_counter += num_leds * self.box_speed.value() / 100.0 / 4.0

        range_leds = list(range(num_leds))
        range_leds = range_leds[int(self.gradient_counter) % num_leds:] + range_leds[:int(self.gradient_counter) % num_leds]

        intensity = self.gradient_intensity.value() / 100.0
        self.label_gradient_intensity.setText(str(self.gradient_intensity.value()) + '%')

        values = []
        for i in reversed(range_leds):
            r, g, b = colorsys.hsv_to_rgb(1.0*i/(num_leds-1), 1, intensity)
            values.append(int(r*255))
            values.append(int(g*255))
            values.append(int(b*255))
            if num_channels == 4:
                values.append(0)

        self.led_strip.set_led_values(0, values)
Ejemplo n.º 26
0
 def online_list_song_download(self):
     widget = self.managePage.playlistWidget
     playlist = widget.get_playlist()
     selecteds = widget.selectedIndexes()
     isExistsSongs = []
     for index in selecteds:
         if index.column() == 0:
             row = index.row()
             songLink = playlist.get_music_path_at(row)
             title = playlist.get_music_title_at(row)
             musicId = playlist.get_music_id_at(row)
             album = playlist.get_music_album_at(row)
             musicName = get_full_music_name_from_title(title)
             musicPath = os.path.join(self.managePage.get_download_dir(), musicName)
             musicPathO = os.path.join(Configures.MusicsDir, musicName)
             if  os.path.exists(musicPath):
                 isExistsSongs.append('%s : %s'%(title, musicPath))
                 continue
             if os.path.exists(musicPathO):
                 isExistsSongs.append('%s : %s'%(title, musicPathO))
                 continue
             self.managePage.downloadPage.add_a_download_work(songLink, musicPath, title, album, musicId, 0, self.managePage.get_threading_lock())
     if len(isExistsSongs):
         existsSongs = '\n'.join(isExistsSongs)
         QMessageBox.information(self, "提示", 
             "以下歌曲已在下载目录中不再进行下载,您可以在不联网的情况下点击在线列表播放!\n%s"%existsSongs)
Ejemplo n.º 27
0
    def show_protocol_selection_in_interpretation(self, start_message, start, end_message, end):
        try:
            cfc = self.compare_frame_controller
            msg_total = 0
            last_sig_frame = None
            for protocol in cfc.protocol_list:
                if not protocol.show:
                    continue
                n = protocol.num_messages
                view_type = cfc.ui.cbProtoView.currentIndex()
                messages = [i - msg_total for i in range(msg_total, msg_total + n) if start_message <= i <= end_message]
                if len(messages) > 0:
                    try:
                        signal_frame = next((sf for sf, pf in self.signal_protocol_dict.items() if pf == protocol))
                    except StopIteration:
                        QMessageBox.critical(self, self.tr("Error"),
                                             self.tr("Could not find corresponding signal frame."))
                        return
                    signal_frame.set_roi_from_protocol_analysis(min(messages), start, max(messages), end + 1, view_type)
                    last_sig_frame = signal_frame
                msg_total += n
            focus_frame = last_sig_frame
            if last_sig_frame is not None:
                self.signal_tab_controller.ui.scrollArea.ensureWidgetVisible(last_sig_frame, 0, 0)

            QApplication.instance().processEvents()
            self.ui.tabWidget.setCurrentIndex(0)
            if focus_frame is not None:
                focus_frame.ui.txtEdProto.setFocus()
        except Exception as e:
            logger.exception(e)
Ejemplo n.º 28
0
    def initialize(self) -> None:
        super().initialize()
        # Initialize the package manager to remove and install scheduled packages.
        self._package_manager = self._package_manager_class(self, parent = self)

        self._mesh_file_handler = MeshFileHandler(self) #type: MeshFileHandler
        self._workspace_file_handler = WorkspaceFileHandler(self) #type: WorkspaceFileHandler

        # Remove this and you will get Windows 95 style for all widgets if you are using Qt 5.10+
        self.setStyle("fusion")

        self.setAttribute(Qt.AA_UseDesktopOpenGL)
        major_version, minor_version, profile = OpenGLContext.detectBestOpenGLVersion()

        if major_version is None and minor_version is None and profile is None and not self.getIsHeadLess():
            Logger.log("e", "Startup failed because OpenGL version probing has failed: tried to create a 2.0 and 4.1 context. Exiting")
            QMessageBox.critical(None, "Failed to probe OpenGL",
                                 "Could not probe OpenGL. This program requires OpenGL 2.0 or higher. Please check your video card drivers.")
            sys.exit(1)
        else:
            opengl_version_str = OpenGLContext.versionAsText(major_version, minor_version, profile)
            Logger.log("d", "Detected most suitable OpenGL context version: %s", opengl_version_str)
        if not self.getIsHeadLess():
            OpenGLContext.setDefaultFormat(major_version, minor_version, profile = profile)

        self._qml_import_paths.append(os.path.join(os.path.dirname(sys.executable), "qml"))
        self._qml_import_paths.append(os.path.join(self.getInstallPrefix(), "Resources", "qml"))

        Logger.log("i", "Initializing job queue ...")
        self._job_queue = JobQueue()
        self._job_queue.jobFinished.connect(self._onJobFinished)

        Logger.log("i", "Initializing version upgrade manager ...")
        self._version_upgrade_manager = VersionUpgradeManager(self)
Ejemplo n.º 29
0
 def musics_added(self, showAddInfo):
     widget = self.managePage.playlistWidget
     playlist = widget.get_playlist()
     newAddedTitles = []
     if widget.get_playing_used_state():
         self.playlist_modified()
     for index in widget.addedIndexes:
         title = playlist.get_music_title_at(index)
         newAddedTitles.append((title, Configures.LocalMusicId))
         if playlist.get_name() == Configures.PlaylistFavorite:
             self.playbackPanel.lovedSongs.append(title)
     if playlist.get_name() == Configures.PlaylistFavorite:
         self.playbackPanel.check_favorite()
     if showAddInfo:
         if len(newAddedTitles):
             thread = DownloadLrcThread(newAddedTitles)
             thread.setDaemon(True)
             thread.setName("downloadLrc")
             thread.start()
         addCount = len(widget.files)
         newAddedCount = len(newAddedTitles)
         text = "您选择了%s首歌曲!\n新添加了%s首歌曲,其他歌曲已在列表中不被添加!"%(addCount, newAddedCount)
         if newAddedCount >0 and addCount == newAddedCount:
             text = "已添加%s首歌曲!"%newAddedCount
         if newAddedCount == 0:
             text = "选择的歌曲已在列表中!"
         QMessageBox.information(self, "添加完成", text)   
 def check_newbie_proceed(self):
     """checks if this user has already uploaded enough single alleles to count as experienced;
     if not, a popup warning is generated and bulk upload denied
     """
     if self.settings["modus"] == "staging":
         return True
     
     self.log.debug("Checking if this user is experienced enough...")
     query = "select count(local_name) from alleles"
     success, data = db_internal.execute_query(query, 1, self.log, "Checking for previous uploads", "Database error", self)
     if not success:
         return False
     if data:
         num = data[0][0]
     else:
         num = 0
     if num < min_num_prev_alleles:
         self.log.info("=> User is not experienced enough, yet!")
         msg = "Bulk Fasta upload is for experienced TypeLoader users.\n\n"
         msg += "Please upload at least {} alleles using single Fasta or XML files,\n".format(min_num_prev_alleles)
         msg += "to make sure you are sufficiently familiar with TypeLoader."
         QMessageBox.warning(self, "Hello new user", msg)
         return False
     self.log.info("=> Experienced user")
     return True
Ejemplo n.º 31
0
 def about(self):
     QMessageBox.about(self,'鼠标','你点鼠标了吧,我知道你点了~,你还不承认啊?!!')
Ejemplo n.º 32
0
 def RS(self):
     lasthost = []
     lastport = []
     host, hok = QInputDialog.getText(
         self, '输入主机',
         '请输入主机名或IP地址\n127.0.0.1本地ip就不用输了,直接扫描本地模拟器\n注意!如果配置文件中存在本地端口,则会使用本地端口进行测试,可能会造成检测不到!'
     )
     if hok:
         if not host:
             QMessageBox.warning(self, '错误', '未输入主机名或IP地址')
             return
         else:
             if con.get('Nox', 'portlist'):
                 a = QMessageBox(
                     QMessageBox.Question, '是否使用本地端口',
                     '检测到本地存在模拟器\n是否用本地端口扫描远程端口?(这可能会导致扫描不到远程模拟器,因为端口原因,但是不用手动输入端口)',
                     QMessageBox.Yes | QMessageBox.No)
                 ok = a.exec()
                 if ok == QMessageBox.Yes:
                     portlist = eval(con.get('Nox', 'portlist'))
                     if not con.get('Nox', 'rport'):
                         result = Lan.Connects(host, portlist)
                         if not result:
                             QMessageBox.warning(self, '错误', '未开启模拟器')
                         elif 'unknow' in result:
                             QMessageBox.warning(self, '错误', '未知的主机名或IP地址')
                         else:
                             con.set('Nox', 'rhost', '[\'' + host + '\']')
                             con.set('Nox', 'rport', str(list(set(result))))
                             con.write(open('config.ini', 'w'))
                             QMessageBox.information(
                                 self, '完成', '远程主机扫描完成,刷新设备会检测链接')
                     else:
                         result = Lan.Connects(host, portlist)
                         if not result:
                             QMessageBox.warning(self, '错误', '未开启模拟器')
                         elif 'unknow' in result:
                             QMessageBox.warning(self, '错误', '未知的主机名或IP地址')
                         else:
                             lasthost += eval(con.get('Nox', 'rhost'))
                             lasthost.append(host)
                             lastport += eval(con.get('Nox', 'rport'))
                             lastport += (list(set(result)))
                             con.set('Nox', 'rhost',
                                     str(list(set(lasthost))))
                             con.set('Nox', 'rport',
                                     str(list(set(lastport))))
                             con.write(open('config.ini', 'w'))
                             QMessageBox.information(
                                 self, '完成', '远程主机扫描完成,刷新设备会检测链接')
                 else:
                     port, pok = QInputDialog.getInt(
                         self, '输入端口号', '请输入远程主机模拟器所开启的端口')
                     if pok:
                         if not port or port > 65535 or port < 0:
                             QMessageBox.warning(self, '错误',
                                                 '为输入端口号,或端口号不正确')
                             return
                         if not con.get('Nox', 'rport'):
                             result = Lan.Connects(host, [port])
                             if not result:
                                 QMessageBox.warning(self, '错误', '未开启模拟器')
                             elif 'unknow' in result:
                                 QMessageBox.warning(
                                     self, '错误', '未知的主机名或IP地址')
                             else:
                                 con.set('Nox', 'rhost',
                                         '[\'' + host + '\']')
                                 con.set('Nox', 'rport',
                                         str(list(set(result))))
                                 con.write(open('config.ini', 'w'))
                                 QMessageBox.information(
                                     self, '完成', '远程主机扫描完成,刷新设备会检测链接')
                         else:
                             result = Lan.Connects(host, [port])
                             if not result:
                                 QMessageBox.warning(self, '错误', '未开启模拟器')
                             elif 'unknow' in result:
                                 QMessageBox.warning(
                                     self, '错误', '未知的主机名或IP地址')
                             else:
                                 lasthost += eval(con.get('Nox', 'rhost'))
                                 lasthost.append(host)
                                 lastport += eval(con.get('Nox', 'rport'))
                                 lastport += (list(set(result)))
                                 con.set('Nox', 'rhost',
                                         str(list(set(lasthost))))
                                 con.set('Nox', 'rport',
                                         str(list(set(lastport))))
                                 con.write(open('config.ini', 'w'))
                                 QMessageBox.information(
                                     self, '完成', '远程主机扫描完成,刷新设备会检测链接')
             else:
                 port, pok = QInputDialog.getInt(self, '输入端口号',
                                                 '请输入远程主机模拟器所开启的端口')
                 if pok:
                     if not port or port > 65535 or port < 0:
                         QMessageBox.warning(self, '错误', '为输入端口号,或端口号不正确')
                         return
                     if not con.get('Nox', 'rport'):
                         result = Lan.Connects(host, [port])
                         if not result:
                             QMessageBox.warning(self, '错误', '未开启模拟器')
                         elif 'unknow' in result:
                             QMessageBox.warning(self, '错误', '未知的主机名或IP地址')
                         else:
                             con.set('Nox', 'rhost', '[\'' + host + '\']')
                             con.set('Nox', 'rport', str(list(set(result))))
                             con.write(open('config.ini', 'w'))
                             QMessageBox.information(
                                 self, '完成', '远程主机扫描完成,刷新设备会检测链接')
                     else:
                         result = Lan.Connects(host, [port])
                         if not result:
                             QMessageBox.warning(self, '错误', '未开启模拟器')
                         elif 'unknow' in result:
                             QMessageBox.warning(self, '错误', '未知的主机名或IP地址')
                         else:
                             lasthost += eval(con.get('Nox', 'rhost'))
                             lasthost.append(host)
                             lastport += eval(con.get('Nox', 'rport'))
                             lastport += (list(set(result)))
                             con.set('Nox', 'rhost',
                                     str(list(set(lasthost))))
                             con.set('Nox', 'rport',
                                     str(list(set(lastport))))
                             con.write(open('config.ini', 'w'))
                             QMessageBox.information(
                                 self, '完成', '远程主机扫描完成,刷新设备会检测链接')
Ejemplo n.º 33
0
                QMessageBox.critical(self, '未知的文件/目录', '请选择正确的文件/目录')
                return
            con.set('Nox', 'dir', set_Dialog.Nox_text.text())
            con.set('General', 'exec',
                    '/'.join(set_Dialog.Adb_text.text().split('/')[:-1]))
            con.write(open('config.ini', 'w'))

if __name__ == '__main__':
    try:
        os.chdir(popen('cd').read().strip('\n'))
        app = QApplication(sys.argv)
        win = MainWin()

        key = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            r'Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Compatibility Assistant\Store'
        )

        if not os.path.exists('config.ini'):
            raise FileNotFoundError
        con = ConfigParser()
        con.read('config.ini', encoding='utf8')
        win.show()
        sys.exit(app.exec())
    except FileNotFoundError:
        QMessageBox.critical(win, '错误', '未找到config.ini\n请验证文件完整性')
        sys.exit(1)
    except Exception as e:
        print(e)
        sys.exit(2)
Ejemplo n.º 34
0
def qmessagebox(text, resource=":/reusingcode/qmessagebox"):
    m = QMessageBox()
    m.setWindowIcon(QIcon(resource))
    m.setIcon(QMessageBox.Information)
    m.setText(text)
    m.exec_()
Ejemplo n.º 35
0
	def makeDir(self):
		self.createPj()
		self.copyFile()
		self.createJson()
		QMessageBox.information(self, "提示", "创建成功!")
		self.close()
Ejemplo n.º 36
0
 def show_about_qt(self):
     """Show About Qt Dialog."""
     QMessageBox.aboutQt(self, translations.TR_ABOUT_QT)
Ejemplo n.º 37
0
 def msg_box(self, title, message, type):
     msg = QMessageBox(self)
     msg.setIcon(type)
     msg.setWindowTitle(title)
     msg.setText(message)
     msg.addButton('Ok', QMessageBox.AcceptRole)
     msg.exec()
Ejemplo n.º 38
0
		def commit():
			msgbox = QMessageBox(self)
			msgbox.setIcon(QMessageBox.Question)
			msgbox.setWindowTitle('Type of gallery source')
			msgbox.setInformativeText('What type of gallery source is it?')
			dir = msgbox.addButton('Directory', QMessageBox.YesRole)
			archive = msgbox.addButton('Archive', QMessageBox.NoRole)
			msgbox.exec()
			new_path = ''
			if msgbox.clickedButton() == dir:
				new_path = QFileDialog.getExistingDirectory(self, 'Choose directory')
			elif msgbox.clickedButton() == archive:
				new_path = QFileDialog.getOpenFileName(self, 'Choose archive',
										   filter=utils.FILE_FILTER)
				new_path = new_path[0]
			else: return None
			if new_path:
				g = utils.update_gallery_path(new_path, gallery)
				self.UPDATE_SIGNAL.emit(g)
				self.close()
Ejemplo n.º 39
0
 def ImageSizeError(self):
     QMessageBox.critical(self,"错误","图片过大",QMessageBox.Yes|QMessageBox.No,QMessageBox.Yes)
Ejemplo n.º 40
0
class ClientMainWindow(QMainWindow):
    def __init__(self, database, transport, keys):
        super().__init__()

        self.database = database
        self.transport = transport

        self.decrypter = PKCS1_OAEP.new(keys)

        uic.loadUi('ClientMainWindow.ui', self)
        self.setWindowTitle('Server connection parameters')

        # self.menu_exit.triggered.connect(qApp.exit)
        self.actionExit.triggered.connect(qApp.exit)

        # contacts ##########################################################
        self.btn_add_contact.clicked.connect(self.add_contact_window)
        # self.menu_add_contact.triggered.connect(self.add_contact_window)
        self.btn_remove_contact.clicked.connect(self.delete_contact)
        # self.menu_del_contact.triggered.connect(self.delete_contact_window)

        self.btn_clear.clicked.connect(self.text_message.clear)
        self.btn_send.clicked.connect(self.send_message)

        self.contacts_model = None
        self.history_model = None

        self.messages = QMessageBox()

        self.current_chat = None
        self.current_chat_key = None
        self.encryptor = None

        self.list_contacts.doubleClicked.connect(self.select_active_user)
        self.clients_list_update()
        self.set_disabled_input()
        self.show()

    ##########################################################################
    def send_message(self):
        message_text = self.text_message.toPlainText()
        self.text_message.clear()
        if not message_text:
            return

        message_text_encrypted = self.encryptor.encrypt(
            message_text.encode('utf8'))
        message_text_encrypted_base64 = base64.b64encode(
            message_text_encrypted)

        try:
            self.transport.send_message(
                self.current_chat,
                message_text_encrypted_base64.decode('ascii'))
            pass
        except ServerError as err:
            self.messages.critical(self, 'Ошибка', err.text)
        except OSError as err:
            if err.errno:
                self.messages.critical(self, 'Ошибка',
                                       'Потеряно соединение с сервером!')
                self.close()
            self.messages.critical(self, 'Ошибка', 'Таймаут соединения 2!')
        except (ConnectionResetError, ConnectionAbortedError):
            self.messages.critical(self, 'Ошибка',
                                   'Потеряно соединение с сервером!')
            self.close()
        else:
            self.database.save_message(self.current_chat, 'out', message_text)
            LOGGER.debug(
                f'Отправлено сообщение для {self.current_chat}: {message_text}'
            )
            self.history_list_update()

    ##########################################################################
    def history_list_update(self):
        list = sorted(self.database.get_history(self.current_chat),
                      key=lambda item: item[3])
        if not self.history_model:
            self.history_model = QStandardItemModel()
            self.list_messages.setModel(self.history_model)
        # Очистим от старых записей
        self.history_model.clear()
        # Берём не более 20 последних записей.
        length = len(list)
        start_index = 0
        if length > 20:
            start_index = length - 20
        for i in range(start_index, length):
            item = list[i]
            if item[1] == 'in':
                mess = QStandardItem(
                    f'Входящее от {item[3].replace(microsecond=0)}:\n {item[2]}'
                )
                mess.setEditable(False)
                mess.setBackground(QBrush(QColor(255, 213, 213)))
                mess.setTextAlignment(Qt.AlignLeft)
                self.history_model.appendRow(mess)
            else:
                mess = QStandardItem(
                    f'Исходящее от {item[3].replace(microsecond=0)}:\n {item[2]}'
                )
                mess.setEditable(False)
                mess.setTextAlignment(Qt.AlignRight)
                mess.setBackground(QBrush(QColor(204, 255, 204)))
                self.history_model.appendRow(mess)
        self.list_messages.scrollToBottom()

    ##########################################################################
    def select_active_user(self):
        self.current_chat = self.list_contacts.currentIndex().data()
        self.set_active_user()

    ##########################################################################
    def set_active_user(self):

        try:
            self.current_chat_key = self.transport.key_request(
                self.current_chat)
            LOGGER.debug(f'Загружен открытый ключ для {self.current_chat}')
            if self.current_chat_key:
                self.encryptor = PKCS1_OAEP.new(
                    RSA.import_key(self.current_chat_key))
        except (OSError, json.JSONDecodeError):
            self.current_chat_key = None
            self.encryptor = None
            LOGGER.debug(f'Не удалось получить ключ для {self.current_chat}')

        # Если ключа нет то ошибка, что не удалось начать чат с пользователем
        if not self.current_chat_key:
            self.messages.warning(
                self, 'Ошибка',
                'Для выбранного пользователя нет ключа шифрования.')
            return

        # Ставим надпись и активируем кнопки
        self.label_new_message.setText(
            f'Введите сообщенние для {self.current_chat}:')
        self.btn_clear.setDisabled(False)
        self.btn_send.setDisabled(False)
        self.text_message.setDisabled(False)

        self.history_list_update()

    ##########################################################################
    def set_disabled_input(self):
        # Надпись  - получатель.
        self.label_new_message.setText(
            'Для выбора получателя дважды кликните на нем в окне контактов.')
        self.text_message.clear()
        if self.history_model:
            self.history_model.clear()

        # Поле ввода и кнопка отправки неактивны до выбора получателя.
        self.btn_clear.setDisabled(True)
        self.btn_send.setDisabled(True)
        self.text_message.setDisabled(True)

    ##########################################################################
    def delete_contact(self):
        LOGGER.info("delete contact")

        if not self.list_contacts.selectedIndexes():
            msg = "No contact selected for delete"
            LOGGER.info(msg)
            self.messages.information(self, 'Delete contact', msg,
                                      QMessageBox.Ok)

            return
        item = self.contacts_model.item(
            self.list_contacts.selectedIndexes()[0].row()).text()

        selected = item
        try:
            self.transport.remove_contact(selected)
        except ServerError as err:
            self.messages.critical(self, 'Ошибка сервера', err.text)
        except OSError as err:
            if err.errno:
                self.messages.critical(self, 'Ошибка',
                                       'Потеряно соединение с сервером!')
                self.close()
            self.messages.critical(self, 'Ошибка', 'Таймаут соединения!')
        else:
            self.database.del_contact(selected)
            self.clients_list_update()
            msg = f'Успешно удалён контакт "{selected}"'
            LOGGER.info(msg)
            self.messages.information(self, 'Delete contact', msg,
                                      QMessageBox.Ok)

    ##########################################################################
    def add_contact_window(self):
        global select_dialog
        select_dialog = AddContactDialog(self.transport, self.database)
        select_dialog.btn_add.clicked.connect(
            lambda: self.add_contact_action(select_dialog))
        select_dialog.show()

    ##########################################################################
    def add_contact_action(self, item):
        new_contact = item.selector.currentText()
        self.add_contact(new_contact)
        item.close()

    ##########################################################################
    def add_contact(self, new_contact):
        try:
            self.transport.add_contact(new_contact)
        except ServerError as err:
            self.messages.critical(self, 'Ошибка сервера', err.text)
        except OSError as err:
            if err.errno:
                self.messages.critical(self, 'Ошибка',
                                       'Потеряно соединение с сервером!')
                self.close()
            self.messages.critical(self, 'Ошибка', 'Таймаут соединения!')
        else:
            self.database.add_contact(new_contact)
            new_contact = QStandardItem(new_contact)
            new_contact.setEditable(False)
            self.contacts_model.appendRow(new_contact)
            msg = f'Успешно добавлен контакт "{new_contact.text()}"'
            LOGGER.info(msg)
            self.messages.information(self, 'Success', msg, QMessageBox.Ok)

    ##########################################################################
    def make_connection(self, trans_obj):
        trans_obj.new_message.connect(self.message)
        trans_obj.connection_lost.connect(self.connection_lost)

    ##########################################################################
    @pyqtSlot(dict)
    def message(self, message):
        '''
        Слот обработчик поступаемых сообщений, выполняет дешифровку
        поступаемых сообщений и их сохранение в истории сообщений.
        Запрашивает пользователя если пришло сообщение не от текущего
        собеседника. При необходимости меняет собеседника.
        '''
        # Получаем строку байтов
        encrypted_message = base64.b64decode(message[MESSAGE_TEXT])
        # Декодируем строку, при ошибке выдаём сообщение и завершаем функцию
        try:
            decrypted_message = self.decrypter.decrypt(encrypted_message)
        except (ValueError, TypeError):
            self.messages.warning(self, 'Ошибка',
                                  'Не удалось декодировать сообщение.')
            return
        # Сохраняем сообщение в базу и обновляем историю сообщений или
        # открываем новый чат.
        self.database.save_message(self.current_chat, 'in',
                                   decrypted_message.decode('utf8'))

        sender = message[SENDER]
        if sender == self.current_chat:
            self.history_list_update()
        else:
            # Проверим есть ли такой пользователь у нас в контактах:
            if self.database.check_contact(sender):
                # Если есть, спрашиваем и желании открыть с ним чат и открываем
                # при желании
                if self.messages.question(
                        self, 'Новое сообщение',
                        f'Получено новое сообщение от {sender}, открыть чат с ним?',
                        QMessageBox.Yes, QMessageBox.No) == QMessageBox.Yes:
                    self.current_chat = sender
                    self.set_active_user()
            else:
                print('NO')
                # Раз нету,спрашиваем хотим ли добавить юзера в контакты.
                if self.messages.question(
                        self, 'Новое сообщение',
                        f'Получено новое сообщение от {sender}.\n Данного пользователя нет в вашем контакт-листе.\n Добавить в контакты и открыть чат с ним?',
                        QMessageBox.Yes, QMessageBox.No) == QMessageBox.Yes:
                    self.add_contact(sender)
                    self.current_chat = sender
                    # Нужно заново сохранить сообщение, иначе оно будет потеряно,
                    # т.к. на момент предыдущего вызова контакта не было.
                    self.database.save_message(
                        self.current_chat, 'in',
                        decrypted_message.decode('utf8'))
                    self.set_active_user()

    ##########################################################################
    # @pyqtSlot()
    def connection_lost(self):
        self.messages.warning(self, 'Сбой соединения',
                              'Потеряно соединение с сервером. ')
        self.close()

    ##########################################################################
    def clients_list_update(self):
        contacts_list = self.database.get_contacts()
        self.contacts_model = QStandardItemModel()
        for i in sorted(contacts_list):
            item = QStandardItem(i)
            item.setEditable(False)
            self.contacts_model.appendRow(item)
        self.list_contacts.setModel(self.contacts_model)
Ejemplo n.º 41
0
 def OnTrayIconMsgClicked(self):
     QMessageBox.information(self, "提示", "小兔子乖乖,把门儿开开。", QMessageBox.Ok)
Ejemplo n.º 42
0
 def checkall(self):
     if self.started is True:
         # new_text = ""
         new_text = []
         new_text_broken = ""
         QApplication.processEvents()
         a1_ps = get_new_a1p(self.codes)
         b1_vs = get_new_b1v(self.codes)
         if len(a1_ps) != len(self.codes) or len(b1_vs) != len(self.codes):
             if DEBUG == 1:
                 get_code = self.codes
                 append_code = ""
                 for codee in get_code:
                     append_code = append_code + ' ' + codee
                 for a1pss in self.a1_ps:
                     append_code = append_code + ' ' + a1pss
                 for b1vss in self.b1_vs:
                     append_code = append_code + ' ' + b1vss
             QMessageBox.question(self, "警告",
                                  "检测到股票代码输入错误,请重新输入" + append_code,
                                  QMessageBox.Ok | QMessageBox.Cancel,
                                  QMessageBox.Ok)
             self.started = False
             self.dlg.label.setText("暂停")
             self.pushButton_2.setEnabled(True)
             self.pushButton_2.setText("开始运行")
         signal = False
         for code, a1_p, b1_v in zip(self.codes, a1_ps, b1_vs):
             QApplication.processEvents()
             if code in self.broken_signal and self.broken_signal[code] > 0:
                 self.broken_signal[code] -= 1
             # use a1_p == 0.00 to judge if limit has been broken
             if a1_p == 0:
                 # limit keeped, watch its volume
                 # print(code + " 封停")
                 if code not in self.b1_v_prev:
                     self.b1_v_prev[code] = b1_v
                 else:
                     if b1_v / self.b1_v_prev[code] < THRESHOLD:
                         if b1_v / self.b1_v_prev[code] < HIGH_THRESHOLD or \
                                 (code in self.broken_signal and self.broken_signal[code] > 0):
                             # new_text = new_text + code + " 出现开板迹象\n"
                             new_text.append(code)
                             # os.system('say "warning"')
                             winsound.Beep(500, 500)
                             signal = True
                         self.broken_signal[code] = 10
                     if DEBUG == 1:
                         # new_text = new_text + code + " 出现开板迹象\n"
                         new_text.append(code)
                         # os.system('say "warning"')
                         winsound.Beep(500, 500)
                         signal = True
                         self.broken_signal[code] = 10
                     self.b1_v_prev[code] = b1_v
             else:
                 # print(code + " 未封停")
                 new_text_broken = new_text_broken + code + " 已经开板\n"
                 if DEBUG == 1:
                     new_text.append(code)
                     signal = True
         if signal is True:
             self.dlg.warn()
         # assign alert code to buttons
         QApplication.processEvents()
         self.code_list = new_text
         for button, text in zip(self.button_list, new_text):
             button.setText(text)
             button.move(BUTTON_X, button.y())
         # button remained should be evicted
         alert_codes = len(new_text)
         for button in self.button_list:
             alert_codes -= 1
             if alert_codes < 0:
                 button.setText("none")
                 button.move(BUTTON_NONE_X, button.y())
         self.dlg.label_broken.setText(new_text_broken)
Ejemplo n.º 43
0
    def decline_invitation(self, index):
        item = self.invitations_list[index]
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Warning)
        msg.setText(f"Czy odrzucić zaprosznie od {item['sender_name']}?")
        msg.setWindowTitle("Odrzucanie zaproszenia")
        msg.setStandardButtons(QMessageBox.Yes | QMessageBox.Abort)
        respond = msg.exec_()
        msg.show()

        if respond == 16384:
            self.remove_invitation(index)
Ejemplo n.º 44
0
    def __init__(self) -> None:
        if hasattr(Qt, 'AA_EnableHighDpiScaling'):
            QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
        if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
            QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)

        self.app = QApplication(sys.argv)

        if settings.vara_cfg()["config_file"].value is None:
            err = QMessageBox()
            err.setIcon(QMessageBox.Warning)
            err.setWindowTitle("Missing config file.")
            err.setText(
                "Could not find VaRA config file.\n"
                "Should we create a config file in the current folder?")

            err.setStandardButtons(
                tp.cast(QMessageBox.StandardButtons,
                        QMessageBox.Yes | QMessageBox.No))
            answer = err.exec_()
            if answer == QMessageBox.Yes:
                settings.save_config()
            else:
                sys.exit()

        self.main_window = CsGenMainWindow()
Ejemplo n.º 45
0
 def search_func(self,Dialog):
         _translate = QtCore.QCoreApplication.translate
         global cusname,cusdob,cusgen,cusocc,cusphone,cusaadhar, cusaddress,cusstate,cuscity,cuspincode,cusatype,cusnominee,cusbalance
         cusname=cusgen=cusocc=cusphone=cusaadhar=cusaddress=cusstate=cuscity=cuspincode=cusatype=cusnominee=cusbalance="null"
         global ano
         ano=self.acc_no.text()
         try:
                 if ano!='':
                         cur.execute('''SELECT accno FROM viewtable''')
                         result=cur.fetchall()
                         b=[]
                         for i in result:
                                 b.append(i[0])
                 
                         if int(ano) in b:
                                 cur.execute("select * FROM viewtable WHERE accno = ? ",(ano,))
                                 result=cur.fetchall()
                                 for db in result:
                                         cusname=db[1]
                                         cusdob=db[2]
                                         cusgen=db[3]
                                         cusocc=db[4]
                                         cusphone=db[5]
                                         cusaadhar=db[6]
                                         cusaddress=db[7]
                                         cusstate=db[8]
                                         cuscity=db[9]
                                         cuspincode=db[10]
                                         cusatype=db[11]
                                         cusnominee=db[12]
                                         cusbalance=db[13]
                                         self.first_name.setText(_translate("view_details",str(cusname)))
                                         self.dob.setText(_translate("view_details",str(cusdob)))
                                         self.gender.setText(_translate("view_details",str(cusgen)))
                                         self.phoneno.setText(_translate("view_details",str(cusphone)))
                                         self.aadhar.setText(_translate("view_details",str(cusaadhar)))
                                         self.addressline_1.setText(_translate("view_details",str(cusaddress)))
                                         self.state.setText(_translate("view_details",str(cusstate)))
                                         self.city.setText(_translate("view_details",str(cuscity)))
                                         self.pincode.setText(_translate("view_details",str(cuspincode)))
                                         self.account_type.setText(_translate("view_details",str(cusatype)))
                                         self.nominee.setText(_translate("view_details",str(cusnominee)))
                                         self.balance.setText(_translate("view_details",str(cusbalance)))
                                         self.state_edit_btn.clicked.connect(lambda: self.state.setReadOnly(False))
                                         self.city_edit_btn.clicked.connect(lambda: self.city.setReadOnly(False))
                                         self.pincode_edit_btn.clicked.connect(lambda:self.pincode.setReadOnly(False))
                                         self.phn_edit_btn.clicked.connect(lambda: self.phoneno.setReadOnly(False)) 
                                         self.addr_edit_button.clicked.connect(lambda: self.addressline_1.setReadOnly(False))
                         
                         else:
                                 msg=QMessageBox()
                                 msg.setIcon(QMessageBox.Warning)
                                 msg.setText("account no. doesnot exit ")
                                 msg.setWindowTitle("error")
                                 msg.exec_()                                
                                 
                 else :
                         msg=QMessageBox()
                         msg.setIcon(QMessageBox.Warning)
                         msg.setText("Enter Valid acc no")
                         msg.setWindowTitle("error")
                         msg.exec_()                
         except ValueError as e:
                 msg=QMessageBox()
                 msg.setIcon(QMessageBox.Warning)
                 msg.setText("Enter Valid details")
                 msg.setWindowTitle("error")
                 msg.exec_()                
Ejemplo n.º 46
0
    def edit_requested(self):
        from PyQt5.QtWidgets import QMessageBox
        msg = QMessageBox(self)
        msg.setIcon(QMessageBox.Question)
        msg.setStyleSheet("QPushButton{min-width: 100px; min-height: 40px;}")

        msg.setText("Le serveur sera arrêté pour l'édition et les transferts en cours seront arrêtés.\n"
                    "Voulez-vous continuer?")
        msg.setWindowTitle("Éditer")
        msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)

        rval = msg.exec()
        if rval == QMessageBox.Yes:
            # self.UI.frameInfos.setEnabled(self.UI.btnEdit.isChecked())
            if self.streamer:
                self.streamer.stop_server()
            self.set_edit_state(True)
Ejemplo n.º 47
0
class Prozor(QMainWindow):

    def getGeneriraniNalozi(self):
        
        try:
            cursor.execute("SELECT brojNaloga FROM radninalog WHERE generiran = '1'")
        except Error as error:
            print(error)
        nalozi = cursor.fetchall()
        
        naloziStr = ""
        for x in range(len(nalozi)):
            nalozi[x] = str(nalozi[x][0])
            naloziStr += nalozi[x] + ", "
        
        return naloziStr

    def getUcitaniNalozi(self, returnType):
        
        try:
            cursor.execute("SELECT brojNaloga FROM radninalog")
        except Error as error:
            print(error)
        
        nalozi = cursor.fetchall()

        if returnType == "string":
            naloziStr = ""
            for x in range(len(nalozi)):
                nalozi[x] = str(nalozi[x][0])
                naloziStr += nalozi[x] + ", "
            
            return naloziStr
        elif returnType == "list":
            listaNaloga = list()
            for nalog in nalozi:
                listaNaloga.append(int(nalog[0]))
            print(listaNaloga)
            return listaNaloga

    def __init__(self):
        super(Prozor, self).__init__()
        self.setGeometry(200, 200, 800, 250)
        self.setWindowTitle("EMD")
        self.setWindowIcon(QtGui.QIcon('..\LogoEMD.png')) 
        self.initUI()
        self.fileName = ""
        self.radniNalozi = []
        self.tableViewProzor = TableViewProzor()
        self.prikazPodataka = PrikazPodataka.PrikazPodatakaProzor()

    def initUI(self):
        self.label = QtWidgets.QLabel(self)
        self.label.setText("Tablica:")
        self.label.move(10, 20)

        self.label2 = QtWidgets.QLabel(self)
        self.label2.move(60, 27)

        self.generiraniNaloziLabel = QtWidgets.QLabel(self)
        self.generiraniNaloziLabel.setText("Izradeni nalozi: " + self.getGeneriraniNalozi())
        self.generiraniNaloziLabel.move(10, 100)
        self.generiraniNaloziLabel.adjustSize()

        self.ucitaniNalozi = QtWidgets.QLabel(self)
        self.ucitaniNalozi.move(10, 130)
        self.ucitaniNalozi.setText("Ucitani nalozi: " + self.getUcitaniNalozi("string"))
        self.ucitaniNalozi.adjustSize()

        self.butt1 = QtWidgets.QPushButton(self)
        self.butt1.setText("Ucitaj tablicu")
        self.butt1.clicked.connect(self.otvoriTablicu)
        self.butt1.move(10, 60)

        self.ucitajSveButton = QtWidgets.QPushButton(self)
        self.ucitajSveButton.setText("Ucitaj sve naloge u bazu")
        self.ucitajSveButton.adjustSize()
        self.ucitajSveButton.move(120, 60)
        self.ucitajSveButton.hide()
        self.ucitajSveButton.clicked.connect(self.ucitajSveNaloge)

        self.closeButton = QtWidgets.QPushButton(self)
        self.closeButton.setText("Zatvori")
        self.closeButton.move(10, 100)
        self.closeButton.clicked.connect(self.close)
        self.closeButton.hide()

        self.izradiNalogeButton = QtWidgets.QPushButton(self)
        self.izradiNalogeButton.setText("Izradi naloge")
        self.izradiNalogeButton.move(290, 60)
        self.izradiNalogeButton.clicked.connect(self.izradiNaloge)
    
        self.showTableButton = QtWidgets.QPushButton(self)
        self.showTableButton.setText("Prikazi tablicu")
        self.showTableButton.move(390, 60)
        self.showTableButton.hide()
        self.showTableButton.clicked.connect(self.prikaziTablicu)

        self.ucitajOznaceneButton = QtWidgets.QPushButton(self)
        self.ucitajOznaceneButton.setText("Ucitaj oznacene naloge")
        self.ucitajOznaceneButton.adjustSize()
        self.ucitajOznaceneButton.move(500, 60)
        self.ucitajOznaceneButton.hide()
        self.ucitajOznaceneButton.clicked.connect(self.ucitajNaloge)
        
        self.pregledBazeButton = QtWidgets.QPushButton(self)
        self.pregledBazeButton.setText("Pregled i unos podataka")
        self.pregledBazeButton.move(10, 165)
        self.pregledBazeButton.adjustSize()
        self.pregledBazeButton.clicked.connect(self.prikaziPodatke)

        self.izradaRasporedaButton = QtWidgets.QPushButton(self)
        self.izradaRasporedaButton.setText("Izrada rasporeda")
        self.izradaRasporedaButton.move(180, 165)
        self.izradaRasporedaButton.adjustSize()
        self.izradaRasporedaButton.clicked.connect(self.izradaRasporeda)

        self.ucitajPozicijeButton = QtWidgets.QPushButton(self)
        self.ucitajPozicijeButton.setText("Ucitaj sve pozicije")
        self.ucitajPozicijeButton.move(650, 60)
        self.ucitajPozicijeButton.clicked.connect(self.ucitajSvePozicije)
        self.ucitajPozicijeButton.hide()
        self.ucitajPozicijeButton.adjustSize()
        
        self.ucitajOznaceneNacrteButton = QtWidgets.QPushButton(self)
        self.ucitajOznaceneNacrteButton.setText("Ucitaj oznacene nacrte")
        self.ucitajOznaceneNacrteButton.adjustSize()
        self.ucitajOznaceneNacrteButton.move(650, 120)
        self.ucitajOznaceneNacrteButton.clicked.connect(self.ucitajOznaceneNacrte)
        self.ucitajOznaceneNacrteButton.hide()
        
        global progressBarGui
        progressBarGui = QProgressBar(self)
        progressBarGui.setGeometry(10, 200, 300, 20)
        progressBarGui.hide()

        self.popUpWindow = QMessageBox()
        self.popUpWindow.setWindowTitle("Obavjest!")
        self.popUpWindow.setGeometry(400, 300, 50, 50)

        IzradaRasporeda.main()

    def izradaRasporeda(self):
        IzradaRasporeda.reopen()


    def ucitajSvePozicije(self):
        #Loadaj tablicu u memoriju
        self.tableViewProzor.loadTable(self.fileName)
        nacrti = []

        for red in range(self.tableViewProzor.tableModel.rowCount()):
            index = self.tableViewProzor.tableModel.index(red, 3)
            data = str(self.tableViewProzor.tableModel.getData(index))
            if data != "nan":
                nacrti.append(data)
        

        ucitajPozicije(self.fileName, nacrti)
        self.prikazPodataka.updateUiViews()

    def prikaziPodatke(self): 
        self.prikazPodataka.show()

    def ucitajNaloge(self):
        redovi = self.tableViewProzor.selectionModel().selectedIndexes()
        
        for index in sorted(redovi):
            self.radniNalozi.append(float(self.tableViewProzor.tableModel.getData(index)))
        
        print("Ucitavaju se nalozi:", self.radniNalozi)
        ucitajUBazu(self.fileName, self.radniNalozi)
        self.radniNalozi.clear()
        self.ucitaniNalozi.setText("Ucitani nalozi: " + self.getUcitaniNalozi("string"))
        self.ucitaniNalozi.adjustSize()
        self.izradiNalogeButton.show()
        self.prikazPodataka.updateUiViews()
        
    def ucitajOznaceneNacrte(self):
        indexi = self.tableViewProzor.selectionModel().selectedIndexes()
        nacrti = []
        for index in indexi:
            nacrti.append(str(self.tableViewProzor.tableModel.getData(index)))

        ucitajPozicije(self.fileName, nacrti)
        self.prikazPodataka.updateUiViews()

    def prikaziTablicu(self):
        self.tableViewProzor.loadTable(self.fileName)
        self.tableViewProzor.prikaziProzor()        
        self.ucitajOznaceneButton.show()
        self.ucitajOznaceneNacrteButton.show()

    def izradiNaloge(self):
        lista = self.getUcitaniNalozi("list")
        closeDbConnection()
        if rn.main(lista):
            self.popUpWindow.setText("Nalozi su generirani!")
            self.popUpWindow.exec_()
        else:
           self.popUpWindow.setText("GREŠKA!")
           self.popUpWindow.exec_()
        openDbConnection()

    def close(self):
        cursor.close()
        vezaSaBazom.close()
        self.close()

    def update(self):
        self.label.adjustSize()

    def getSviNalozi(self):
        #Loda se tablica u memoriju
        self.tableViewProzor.loadTable(self.fileName)
        
        nalozi = []
        
        for red in range(self.tableViewProzor.tableModel.rowCount()):
            index = self.tableViewProzor.tableModel.index(red, 0)
            data = float(self.tableViewProzor.tableModel.getData(index))
            if str(data) != 'nan':
                nalozi.append(data)

        print(nalozi)
        return nalozi

    def ucitajSveNaloge(self):
        #Ako ucitajUBazu() vraca true, nema errora
        if ucitajUBazu(self.fileName, self.getSviNalozi()):
            self.izradiNalogeButton.show()
            self.ucitaniNalozi.setText("Ucitani nalozi: " + self.getUcitaniNalozi("string"))
            self.ucitaniNalozi.adjustSize()
            self.prikazPodataka.updateUiViews()
            
    
    def otvoriTablicu(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        self.fileName, _ = QFileDialog.getOpenFileName(self,"Odaberi tablicu", "","All Files (*);;Python Files (*.py)", options=options)
        if self.fileName:
            print(self.fileName)
            self.ucitajSveButton.show()
            self.showTableButton.show()
            self.label2.setText(self.fileName)
            self.label2.adjustSize()
            self.tableViewProzor.setImeTablice(self.fileName)
            self.ucitajPozicijeButton.show()
Ejemplo n.º 48
0
    def accept_invitation(self, index):
        item = self.invitations_list[index]
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Warning)
        msg.setText(f"Czy zaakceptować zaprosznie od {item['sender_name']}?")
        msg.setInformativeText(f"Ty i {item['sender_name']} staniecie się znajomymi")
        msg.setWindowTitle("Dodawanie znajomego")
        msg.setStandardButtons(QMessageBox.Yes | QMessageBox.Abort)
        respond = msg.exec_()
        msg.show()

        if respond == 16384:
            self.add_friend(index)
Ejemplo n.º 49
0
    def bugreport(self):
        reporttext = 'Please report all bugs to <a href="mailto:[email protected]">[email protected]</a>' \
                              + ' or <a href="mailto:[email protected]">[email protected]</a>'

        QMessageBox.about(QWidget(), "Report", reporttext)
Ejemplo n.º 50
0
    def initUI(self):
        self.label = QtWidgets.QLabel(self)
        self.label.setText("Tablica:")
        self.label.move(10, 20)

        self.label2 = QtWidgets.QLabel(self)
        self.label2.move(60, 27)

        self.generiraniNaloziLabel = QtWidgets.QLabel(self)
        self.generiraniNaloziLabel.setText("Izradeni nalozi: " + self.getGeneriraniNalozi())
        self.generiraniNaloziLabel.move(10, 100)
        self.generiraniNaloziLabel.adjustSize()

        self.ucitaniNalozi = QtWidgets.QLabel(self)
        self.ucitaniNalozi.move(10, 130)
        self.ucitaniNalozi.setText("Ucitani nalozi: " + self.getUcitaniNalozi("string"))
        self.ucitaniNalozi.adjustSize()

        self.butt1 = QtWidgets.QPushButton(self)
        self.butt1.setText("Ucitaj tablicu")
        self.butt1.clicked.connect(self.otvoriTablicu)
        self.butt1.move(10, 60)

        self.ucitajSveButton = QtWidgets.QPushButton(self)
        self.ucitajSveButton.setText("Ucitaj sve naloge u bazu")
        self.ucitajSveButton.adjustSize()
        self.ucitajSveButton.move(120, 60)
        self.ucitajSveButton.hide()
        self.ucitajSveButton.clicked.connect(self.ucitajSveNaloge)

        self.closeButton = QtWidgets.QPushButton(self)
        self.closeButton.setText("Zatvori")
        self.closeButton.move(10, 100)
        self.closeButton.clicked.connect(self.close)
        self.closeButton.hide()

        self.izradiNalogeButton = QtWidgets.QPushButton(self)
        self.izradiNalogeButton.setText("Izradi naloge")
        self.izradiNalogeButton.move(290, 60)
        self.izradiNalogeButton.clicked.connect(self.izradiNaloge)
    
        self.showTableButton = QtWidgets.QPushButton(self)
        self.showTableButton.setText("Prikazi tablicu")
        self.showTableButton.move(390, 60)
        self.showTableButton.hide()
        self.showTableButton.clicked.connect(self.prikaziTablicu)

        self.ucitajOznaceneButton = QtWidgets.QPushButton(self)
        self.ucitajOznaceneButton.setText("Ucitaj oznacene naloge")
        self.ucitajOznaceneButton.adjustSize()
        self.ucitajOznaceneButton.move(500, 60)
        self.ucitajOznaceneButton.hide()
        self.ucitajOznaceneButton.clicked.connect(self.ucitajNaloge)
        
        self.pregledBazeButton = QtWidgets.QPushButton(self)
        self.pregledBazeButton.setText("Pregled i unos podataka")
        self.pregledBazeButton.move(10, 165)
        self.pregledBazeButton.adjustSize()
        self.pregledBazeButton.clicked.connect(self.prikaziPodatke)

        self.izradaRasporedaButton = QtWidgets.QPushButton(self)
        self.izradaRasporedaButton.setText("Izrada rasporeda")
        self.izradaRasporedaButton.move(180, 165)
        self.izradaRasporedaButton.adjustSize()
        self.izradaRasporedaButton.clicked.connect(self.izradaRasporeda)

        self.ucitajPozicijeButton = QtWidgets.QPushButton(self)
        self.ucitajPozicijeButton.setText("Ucitaj sve pozicije")
        self.ucitajPozicijeButton.move(650, 60)
        self.ucitajPozicijeButton.clicked.connect(self.ucitajSvePozicije)
        self.ucitajPozicijeButton.hide()
        self.ucitajPozicijeButton.adjustSize()
        
        self.ucitajOznaceneNacrteButton = QtWidgets.QPushButton(self)
        self.ucitajOznaceneNacrteButton.setText("Ucitaj oznacene nacrte")
        self.ucitajOznaceneNacrteButton.adjustSize()
        self.ucitajOznaceneNacrteButton.move(650, 120)
        self.ucitajOznaceneNacrteButton.clicked.connect(self.ucitajOznaceneNacrte)
        self.ucitajOznaceneNacrteButton.hide()
        
        global progressBarGui
        progressBarGui = QProgressBar(self)
        progressBarGui.setGeometry(10, 200, 300, 20)
        progressBarGui.hide()

        self.popUpWindow = QMessageBox()
        self.popUpWindow.setWindowTitle("Obavjest!")
        self.popUpWindow.setGeometry(400, 300, 50, 50)

        IzradaRasporeda.main()
Ejemplo n.º 51
0
 def empty_value_message(self, line):
     title = 'Could not add line!'
     message = 'Empty fields in entry. This line will not be added.'
     QMessageBox.warning(self, title, message)
Ejemplo n.º 52
0
 def dialog(message: str) -> None:
     QMessageBox.critical(None, "VirtScreen", message)
Ejemplo n.º 53
0
 def Get_Pos(self):
     self.pos_list = []
     self.checkstat = True
     dig = QMessageBox.information(
         self, "提示", "1.请点击视频中的直行红绿灯坐标!" + "\n\n" + "2.请点击视频中的停车线坐标!",
         QMessageBox.Yes)
Ejemplo n.º 54
0
 def invalid_value_message(self, value):
     title = 'Could not add line!'
     message = "'{}' contains an invalid value.".format(value)
     QMessageBox.warning(self, title, message)
Ejemplo n.º 55
0
    def abort_trans(self):
        """中断传输函数:发送取消消息"""
        self.settings.beginGroup('ClientSetting')
        setting_host = self.settings.value('host', '127.0.0.1')
        setting_port = int(self.settings.value('server_port', 12345))
        self.settings.endGroup()
        try:
            self.file_sender.terminate()  # 关闭当前的发送进程
            self.file_sender.join()
            self.file_sender.close()
            del self.file_sender
        except ValueError:
            pass
        except AttributeError:
            pass

        self.abort_sender = Process(target=trans_client.starter, name='AbortSender',
                                    args=(setting_host, setting_port, '', None, self.client_que))
        self.abort_sender.start()
        self.abort_sender.join(5)
        if self.abort_sender.exitcode is None:  # join超时,未收到中断回包时
            msg_box = QMessageBox(self)
            msg_box.setWindowTitle('警告')
            msg_box.setIcon(QMessageBox.Warning)
            msg_box.setText('接收端无响应!')
            msg_box.addButton('确定', QMessageBox.AcceptRole)
            msg_box.exec()
            self.abort_sender.kill()
            for inst in self.find_instance_by_status('uploading'):
                inst.status = 'error'
                i = self.find_index_by_name(inst.name)
                self.file_table.item(i, 4).setText('传输中断')
            self.ui_pending()
            self.abort_sender.join()
        self.abort_sender.close()
        del self.abort_sender
def alert(msg_qsv):
    msg = msg_qsv.toString()
    QMessageBox.information(Scripter.dialogs.mainWindow.qt, "Alert", msg)
Ejemplo n.º 57
0
def error(errors):
    message = '\n'.join(errors)
    QMessageBox.critical(QMessageBox(), 'Error', message, QMessageBox.Close, QMessageBox.Escape)
Ejemplo n.º 58
0
 def closeEvent(self, event):
     """关闭事件函数:检查是否有传输中的文件并退出"""
     if self.find_instance_by_status('uploading'):
         msg_box = QMessageBox(self)
         msg_box.setWindowTitle('警告')
         msg_box.setIcon(QMessageBox.Warning)
         msg_box.setText('文件传输中,是否中断并退出?')
         msg_box.addButton('确定', QMessageBox.AcceptRole)
         msg_box.addButton('取消', QMessageBox.DestructiveRole)
         reply = msg_box.exec()
         if reply == QMessageBox.AcceptRole:
             self.abort_trans()
             self.safe_close()
             event.accept()
         else:
             event.ignore()
     else:
         self.safe_close()
         event.accept()
Ejemplo n.º 59
0
def warning(warnings):
    message = '\n'.join(warnings)
    QMessageBox.warning(QMessageBox(), 'Warning', message, QMessageBox.Close, QMessageBox.Escape)
Ejemplo n.º 60
0
 def update_prog(self):
     """传输过程管理及进度条更新函数。"""
     try:
         message = self.client_que.get(block=False)
         inst = self.find_instance_by_name(message['name'])  # 考虑到简明视图的性能,不全局计算index
         if message['type'] == 'info':
             if message['message'] == 'MD5_passed':
                 inst.status = 'complete'
                 index = self.find_index_by_name(message['name'])
                 self.file_table.item(index, 4).setText('传输完成')
                 self.file_table.item(index, 2).setText('100 %')
                 self.del_list.append(inst.path)
             elif message['message'] == 'MD5_failed':
                 inst.status = 'error'
                 index = self.find_index_by_name(message['name'])
                 self.file_table.item(index, 4).setText('传输错误')
                 self.file_table.item(index, 2).setText('100 %')
             elif message['message'] == 'aborted':
                 for inst in self.find_instance_by_status('uploading'):
                     inst.status = 'error'
                     i = self.find_index_by_name(inst.name)
                     self.file_table.item(i, 4).setText('传输中断')
                 self.ui_pending()
                 self.prog_timer.stop()
             # 若无上传中的文件且未被中断,关闭传输进程,清空上传列表且提示完成结果
             if not self.find_instance_by_status('uploading') and self.prog_timer.isActive():
                 self.Lclient_status.setText(
                     '''传输完成:<font color=green>{0}<font color=black>/<font color=red>{1}<font color=black>/0 
                     (<font color=green>Comp<font color=black>/<font color=red>Err<font color=black>/Up)'''.format(
                         len(self.find_instance_by_status('complete')), len(self.find_instance_by_status('error'))))
                 self.file_sender.terminate()
                 self.file_sender.join()
                 self.file_sender.close()
                 self.prog_timer.stop()
                 if self.del_list and not self.find_instance_by_status('error'):
                     # 待删除列表不为空且没有传输错误则考虑是否删除源文件
                     self.settings.beginGroup('ClientSetting')
                     setting_del_source = int(self.settings.value('del_source', False))
                     self.settings.endGroup()
                     if setting_del_source:
                         msg_box = QMessageBox(self)
                         msg_box.setWindowTitle('成功')
                         msg_box.setIcon(QMessageBox.Information)
                         msg_box.setText('传输成功完成!\n点击确定删除源文件')
                         msg_box.addButton('确定', QMessageBox.AcceptRole)
                         msg_box.addButton('取消', QMessageBox.DestructiveRole)
                         reply = msg_box.exec()
                         if reply == QMessageBox.AcceptRole:
                             for path in self.del_list:
                                 try:
                                     os.remove(path)
                                 except Exception as e:
                                     msg_box = QMessageBox(self)
                                     msg_box.setWindowTitle('错误')
                                     msg_box.setIcon(QMessageBox.Critical)
                                     msg_box.setInformativeText('无法删除\n{0}'.format(path))
                                     msg_box.setText(repr(e))
                                     msg_box.addButton('确定', QMessageBox.AcceptRole)
                                     msg_box.exec()
                             self.remove_all()
                     else:
                         msg_box = QMessageBox(self)
                         msg_box.setWindowTitle('成功')
                         msg_box.setIcon(QMessageBox.Information)
                         msg_box.setText('传输成功完成!')
                         msg_box.addButton('确定', QMessageBox.AcceptRole)
                         msg_box.exec()
                 else:
                     msg_box = QMessageBox(self)
                     msg_box.setWindowTitle('警告')
                     msg_box.setIcon(QMessageBox.Warning)
                     msg_box.setText('传输完成,但有文件传输出错!')
                     msg_box.addButton('确定', QMessageBox.AcceptRole)
                     msg_box.exec()
                 self.ui_pending()
             else:
                 self.Lclient_status.setText(
                     '''传输中:<font color=green>{0}<font color=black>/<font color=red>{1}<font color=black>/{2} 
                     (<font color=green>Comp<font color=black>/<font color=red>Err<font color=black>/Up)'''.format(
                         len(self.find_instance_by_status('complete')), len(self.find_instance_by_status('error')),
                         len(self.find_instance_by_status('uploading'))))
         elif message['type'] == 'prog':
             inst.prog.setValue(message['part'] + 1)
             if self.setting_detail_view:  # 详细视图:更新进度百分比
                 index = self.find_index_by_name(message['name'])
                 file_prog = message['part'] / inst.prog.maximum() * 100
                 self.file_table.item(index, 2).setText('{0:.2f} %'.format(file_prog))
     except queue.Empty:
         pass