예제 #1
0
파일: qt.py 프로젝트: WuLiFang/cgtwq
def ask_login(parent=None):
    # type: (Any) -> AccountInfo
    """Ask login with a dialog.
        parent (QWidget, optional): Defaults to None. Parent widget.

    Returns:
        cgtwq.AccountInfo: Account logged in.
    """

    _app = application()
    dialog = QDialog(parent)
    account_input = QLineEdit()
    password_input = QLineEdit()
    _setup_login_dialog(dialog, account_input, password_input)

    while True:
        dialog.exec_()
        if dialog.result() == QDialog.Rejected:
            raise ValueError("Rejected")
        account, password = account_input.text(), password_input.text()
        try:
            return cgtwq.login(account, password)
        except (ValueError, cgtwq.AccountNotFoundError, cgtwq.PasswordError) as ex:
            msg = text_type(ex)
            QMessageBox.critical(parent, "登录失败", msg)
예제 #2
0
def createConnection():
    db = QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(":memory:")
    if not db.open():
        QMessageBox.critical(
            None,
            QObject.tr("Cannot open database"),
            QObject.tr("Unable to establish a database connection.\n"
                       "This example needs SQLite support. Please read "
                       "the Qt SQL driver documentation for information how "
                       "to build it.\n\n"
                       "Click Cancel to exit."),
            QMessageBox.Cancel,
        )
        return False

    query = QSqlQuery()
    query.exec_("create table person (id int primary key, "
                "firstname varchar(20), lastname varchar(20))")
    query.exec_("insert into person values(101, 'Danny', 'Young')")
    query.exec_("insert into person values(102, 'Christine', 'Holand')")
    query.exec_("insert into person values(103, 'Lars', 'Gordon')")
    query.exec_("insert into person values(104, 'Roberto', 'Robitaille')")
    query.exec_("insert into person values(105, 'Maria', 'Papadopoulos')")

    query.exec_("create table items (id int primary key,"
                "imagefile int,"
                "itemtype varchar(20),"
                "description varchar(100))")
    query.exec_("insert into items "
                "values(0, 0, 'Qt',"
                "'Qt is a full development framework with tools designed to "
                "streamline the creation of stunning applications and  "
                "amazing user interfaces for desktop, embedded and mobile "
                "platforms.')")
    query.exec_("insert into items "
                "values(1, 1, 'Qt Quick',"
                "'Qt Quick is a collection of techniques designed to help "
                "developers create intuitive, modern-looking, and fluid "
                "user interfaces using a CSS & JavaScript like language.')")
    query.exec_("insert into items "
                "values(2, 2, 'Qt Creator',"
                "'Qt Creator is a powerful cross-platform integrated "
                "development environment (IDE), including UI design tools "
                "and on-device debugging.')")
    query.exec_("insert into items "
                "values(3, 3, 'Qt Project',"
                "'The Qt Project governs the open source development of Qt, "
                "allowing anyone wanting to contribute to join the effort "
                "through a meritocratic structure of approvers and "
                "maintainers.')")

    query.exec_("create table images (itemid int, file varchar(20))")
    query.exec_("insert into images values(0, 'images/qt-logo.png')")
    query.exec_("insert into images values(1, 'images/qt-quick.png')")
    query.exec_("insert into images values(2, 'images/qt-creator.png')")
    query.exec_("insert into images values(3, 'images/qt-project.png')")

    return True
예제 #3
0
def qMsgBoxCritical(parentWidg, titleMsgBx, messageMsgBx, buttonFlagsMsgBxm = QMessageBox.Ok | QMessageBox.Default, defaultBtnMsgBx = QMessageBox.NoButton ):
    qmsgParent = None
    if(parentWidg is not None):
        qmsgParent = parentWidg
    reply = defaultBtnMsgBx
    try:
        reply = QMessageBox.critical(qmsgParent, titleMsgBx, messageMsgBx, buttonFlagsMsgBxm, defaultBtnMsgBx)
    except:
        parentScreen = QtGui.QApplication.desktop().screen(QtGui.QApplication.desktop().primaryScreen())
        qmsgParent = QtGui.QMainWindow(parentScreen)
        reply = QMessageBox.critical(qmsgParent, titleMsgBx, messageMsgBx, buttonFlagsMsgBxm, defaultBtnMsgBx)
    return reply
예제 #4
0
    def __init__(self, parent: QWidget = None):
        super().__init__(parent)

        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)

        self.server = QLocalServer(self)

        if not self.server.listen("fortune"):
            QMessageBox.critical(
                self,
                self.tr("Local Fortune Server"),
                self.tr("Unable to start the server: %s." %
                        (self.server.errorString())),
            )
            QTimer.singleShot(0, self.close)
            return

        statusLabel = QLabel()
        statusLabel.setWordWrap(True)
        statusLabel.setText(
            self.
            tr("The server is running.\nRun the Local Fortune Client example now."
               ))

        self.fortunes = (
            self.tr(
                "You've been leading a dog's life. Stay off the furniture."),
            self.tr("You've got to think about tomorrow."),
            self.tr("You will be surprised by a loud noise."),
            self.tr("You will feel hungry again in another hour."),
            self.tr("You might have mail."),
            self.tr("You cannot kill time without injuring eternity."),
            self.tr(
                "Computers are not intelligent. They only think they are."),
        )

        quitButton = QPushButton(self.tr("Quit"))
        quitButton.setAutoDefault(False)
        quitButton.clicked.connect(self.close)
        self.server.newConnection.connect(self.sendFortune)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout(self)
        mainLayout.addWidget(statusLabel)
        mainLayout.addLayout(buttonLayout)

        self.setWindowTitle(QGuiApplication.applicationDisplayName())
예제 #5
0
def critical_message(message, parent=None):
    """
    Shows a critical message
    :param message: str
    :param parent: QWidget
    """

    parent = None
    message_box = QMessageBox(parent)
    flags = message_box.windowFlags(
    ) ^ Qt.WindowContextHelpButtonHint | Qt.WindowStaysOnTopHint
    message_box.setWindowFlags(flags)
    message_box.critical(parent, 'Critical Error', message)
예제 #6
0
    def start(self):
        self.startButton.setEnabled(False)

        QGuiApplication.setOverrideCursor(Qt.WaitCursor)

        self.bytesWritten = 0
        self.bytesReceived = 0

        while not self.tcpServer.isListening() and not self.tcpServer.listen():
            ret = QMessageBox.critical(
                self,
                self.tr("Loopback"),
                self.tr(
                    "Unable to start the test: %s" % (self.tcpServer.errorString())
                ),
                QMessageBox.Retry | QMessageBox.Cancel,
            )
            if ret == QMessageBox.Cancel:
                return

        self.serverStatusLabel.setText(self.tr("Listening"))
        self.clientStatusLabel.setText(self.tr("Connecting"))
        self.tcpClient.connectToHost(
            QHostAddress.LocalHost, self.tcpServer.serverPort()
        )
예제 #7
0
def show_error(parent, title, error):
    """
    Show a error QMessageBox with the given error
    :return:
    """

    return QMessageBox.critical(parent, title, error)
예제 #8
0
    def write_grid(self):
        """Write generated mesh to file"""

        # Create all the geometrical quantities
        try:
            self.mesh.geometry()
        except (
                ValueError,
                TypeError,
                func_timeout.FunctionTimedOut,
                SolutionError,
        ) as e:
            self._popup_error_message(e)
            return

        if not hasattr(self, "mesh"):
            flags = QMessageBox.StandardButton.Ok
            QMessageBox.critical(self, "Error",
                                 "Can't write mesh to file; no mesh found!",
                                 flags)
            return

        filename, _ = QFileDialog.getSaveFileName(
            self,
            "Save grid to file",
            self.gui_options["grid_file"],
            filter=NETCDF_FILTER,
        )

        if not filename:
            return

        # If there was no extension, add one, unless the file already exists
        path = pathlib.Path(self.filename)
        if not path.exists() and path.suffix == "":
            self.filename += ".nc"

        self.mesh.writeGridfile(filename)
예제 #9
0
def INITIALIZE(additionalPackageLocations=[], software=""):
    sys.path.append(
        str((Path(__file__).parent / Path('Packages')).resolve().absolute()))
    from PyFlow.UI.Tool import REGISTER_TOOL
    from PyFlow.UI.Widgets.InputWidgets import REGISTER_UI_INPUT_WIDGET_PIN_FACTORY
    from PyFlow.UI.Canvas.UINodeBase import REGISTER_UI_NODE_FACTORY
    from PyFlow.UI.Canvas.UIPinBase import REGISTER_UI_PIN_FACTORY
    from PyFlow import ConfigManager
    from Qt.QtWidgets import QMessageBox

    packagePaths = Packages.__path__

    def ensurePackagePath(inPath):
        for subFolder in os.listdir(inPath):
            subFolderPath = os.path.join(inPath, subFolder)
            if os.path.isdir(subFolderPath):
                if "PyFlow" in os.listdir(subFolderPath):
                    subFolderPath = os.path.join(subFolderPath, "PyFlow",
                                                 "Packages")
                    if os.path.exists(subFolderPath):
                        return subFolderPath
        return inPath

    def recursePackagePaths(inPath):
        paths = []
        for subFolder in os.listdir(inPath):
            subFolderPath = os.path.join(inPath, subFolder)
            if os.path.isdir(subFolderPath):
                if "PyFlow" in os.listdir(subFolderPath):
                    subFolderPath = os.path.join(subFolderPath, "PyFlow",
                                                 "Packages")
                    if os.path.exists(subFolderPath):
                        paths.append(subFolderPath)
        return paths

    # check for additional package locations
    if "PYFLOW_PACKAGES_PATHS" in os.environ:
        delim = ';'
        pathsString = os.environ["PYFLOW_PACKAGES_PATHS"]
        # remove delimeters from right
        pathsString = pathsString.rstrip(delim)
        for packagesRoot in pathsString.split(delim):
            if os.path.exists(packagesRoot):
                paths = recursePackagePaths(packagesRoot)
                packagePaths.extend(paths)

    for packagePathId in range(len(additionalPackageLocations)):
        packagePath = additionalPackageLocations[packagePathId]
        packagePath = ensurePackagePath(packagePath)
        additionalPackageLocations[packagePathId] = packagePath

    packagePaths.extend(additionalPackageLocations)

    for importer, modname, ispkg in pkgutil.iter_modules(packagePaths):
        try:
            if ispkg:
                mod = importer.find_module(modname).load_module(modname)
                package = getattr(mod, modname)()
                __PACKAGES[modname] = package
                __PACKAGE_PATHS[modname] = os.path.normpath(mod.__path__[0])
        except Exception as e:
            QMessageBox.critical(
                None, str("Fatal error"),
                "Error On Module %s :\n%s" % (modname, str(e)))
            continue

    registeredInternalPinDataTypes = set()

    for name, package in __PACKAGES.items():
        packageName = package.__class__.__name__
        for node in package.GetNodeClasses().values():
            node._packageName = packageName

        for pin in package.GetPinClasses().values():
            pin._packageName = packageName
            if pin.IsValuePin():
                internalType = pin.internalDataStructure()
                if internalType in registeredInternalPinDataTypes:
                    raise Exception(
                        "Pin with {0} internal data type already been registered"
                        .format(internalType))
                registeredInternalPinDataTypes.add(internalType)

        uiPinsFactory = package.UIPinsFactory()
        if uiPinsFactory is not None:
            REGISTER_UI_PIN_FACTORY(packageName, uiPinsFactory)

        uiPinInputWidgetsFactory = package.PinsInputWidgetFactory()
        if uiPinInputWidgetsFactory is not None:
            REGISTER_UI_INPUT_WIDGET_PIN_FACTORY(packageName,
                                                 uiPinInputWidgetsFactory)

        uiNodesFactory = package.UINodesFactory()
        if uiNodesFactory is not None:
            REGISTER_UI_NODE_FACTORY(packageName, uiNodesFactory)

        for toolClass in package.GetToolClasses().values():
            supportedSoftwares = toolClass.supportedSoftwares()
            if "any" not in supportedSoftwares:
                if software not in supportedSoftwares:
                    continue
            REGISTER_TOOL(packageName, toolClass)
    getHashableDataTypes()