예제 #1
0
    def __init__(self, engine):
        super().__init__(engine)

        self.component = QQmlComponent(self.engine)
        self.component.loadUrl('src/views/qml/components/PreviewCard.qml')
        self.projects_list = self.root.findChild(QQuickItem, 'projects')
        self.project_to_remove = None
        self.load_projects()
예제 #2
0
    def __init__(self, engine):
        super().__init__(engine)

        self.component = QQmlComponent(self.engine)
        self.component.loadUrl('src/views/qml/components/TemplateListItem.qml')
        self.templates_list = self.root.findChild(QQuickItem,
                                                  'templatesListColumn')
        self.load_templates()
        self.current = None
예제 #3
0
 def _qmlLoad( self, qmlfile ):
     engine = QQmlEngine()
     main_qml = Path(ATHENA_SRC_DIR) / 'qml' / qmlfile
     component = QQmlComponent(engine, main_qml.as_uri() )
     if ( component.status() != QQmlComponent.Ready ):
         print ("Error loading QML:")
         print(component.errorString())
     result = component.create()
     # Need to hold a reference in python to the QQmlComponent, or else
     # PySide2 will helpfully delete the material object along with it
     # after this function ends.
     self._qtrefs.append(component)
     return result
예제 #4
0
 def load(self):
     self.component = component = QQmlComponent(
         self.engine.engine, self.qmlUrl, QQmlComponent.PreferSynchronous)
     assert not component.isLoading()
     if component.isError():
         for err in component.errors():
             print("Error:", err.url(), err.line(), err)
예제 #5
0
## and conditions see https://www.qt.io/terms-conditions. For further
## information use the contact form at https://www.qt.io/contact-us.
##
## GNU General Public License Usage
## Alternatively, this file may be used under the terms of the GNU
## General Public License version 3 as published by the Free Software
## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
## included in the packaging of this file. Please review the following
## information to ensure the GNU General Public License requirements will
## be met: https://www.gnu.org/licenses/gpl-3.0.html.
##
## $QT_END_LICENSE$
##
#############################################################################

import sys
from helper import adjust_filename

from PySide2.QtCore import QUrl
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlEngine, QQmlComponent

app = QGuiApplication(sys.argv)

engine = QQmlEngine()
component = QQmlComponent(engine)

# This should segfault if the QDeclarativeComponent has not QQmlEngine
component.loadUrl(QUrl.fromLocalFile(adjust_filename('foo.qml', __file__)))

예제 #6
0
class TemplateView(View):
    def __init__(self, engine):
        super().__init__(engine)

        self.component = QQmlComponent(self.engine)
        self.component.loadUrl('src/views/qml/components/TemplateListItem.qml')
        self.templates_list = self.root.findChild(QQuickItem,
                                                  'templatesListColumn')
        self.load_templates()
        self.current = None

    def load_templates(self):
        """ Loads all existing templates and creates ui
            entries for them.
        """
        templates = template_controller.get_templates()

        for template in templates:
            self.add_template(template)

    def add_template(self, template):
        """ Creates a ui entry for single template
        """
        item = self.component.create()
        item.setProperty('name', template.name)
        item.setProperty('template_id', template.template_id)
        item.setObjectName(template.template_id)
        item.setParentItem(self.templates_list)
        item.setParent(self.templates_list)

    @Slot(str, str, str)
    def create_template_clicked(self, name, filename, path):
        """ Called when new template button is clicked.
            Creates a new template.

            Args:
                name (string): Name of the template, entered by user
                filename (string): File name of the template entered by user
                path (string): Path of the template, entered by user
        """
        try:
            template = template_controller.create_template(
                name, filename, path, '')
            self.add_template(template)
        except PermissionError:
            self.show_error(get_literal('template_creation_failed'),
                            get_literal('permission_denied'))
        except FileExistsError:
            self.show_error(get_literal('template_already_exists'),
                            get_literal('permission_denied'))
        except InvalidValueError as err:
            self.show_error(get_literal('template_creation_failed'), str(err))

    @Slot(str)
    def remove_template(self, template_id):
        """ Called when remove button is clicked on a template
            Removes the template

            Args:
                template_id (string): Id of the template to remove
        """
        template_controller.remove_template(template_id)

        obj = self.root.findChild(QQuickItem, template_id)
        obj.deleteLater()

    @Slot(str)
    def edit_clicked(self, template_id):
        """ Called when edit button is clicked on a template
            Opens template editing view.

        Args:
            template_id (string): Id of the template to open
                the edit view for
        """
        source = template_controller.get_source(template_id)
        child = self.root.findChild(QObject, 'editTemplateDialog')
        child.setProperty('visible', True)

        child = self.root.findChild(QObject, 'editTemplateDialogContent')
        child.setProperty('text', source)

        self.current = template_id

    @Slot(str)
    def save_clicked(self, source):
        """ Called when save button is clicked. Saves the
            template being edited currently.

            Args:
                source (string): Source of the template to save
        """
        template_store.write(self.current, source)

    @Slot(result=str)
    def get_default_path(self):
        """ Returns default path where templates shall be saved

            Returns:
                string: Default path
        """
        return config.get_value('default_template_path')
예제 #7
0
파일: bug_557.py 프로젝트: zhoub/pyside2
import sys

from PySide2.QtCore import QUrl
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlEngine, QQmlComponent

app = QGuiApplication(sys.argv)

engine = QQmlEngine()
component = QQmlComponent(engine)

# This should segfault if the QDeclarativeComponent has not QQmlEngine
component.loadUrl(QUrl.fromLocalFile('foo.qml'))

    def __init__(self):
        super(ComponentChanger, self).__init__(None)

        self._current_component = QQmlComponent()
        self._changes = []
예제 #9
0
    def initialize(self, size: QSize, shareContext: QOpenGLContext) -> None:
        """
        Initialize offscreen renderer.

        Args:
            size: The size of the area available for rendering.
            shareContext: OpenGL context used as a share context.

        Raises:
            RuntimeError: If the renderer has already been initialized.
        """
        print(f'QmlOffscreenRenderer.initialize: {size}')
        if self.initialized:
            raise RuntimeError('Already initialized')

        format = QSurfaceFormat()
        format.setDepthBufferSize(16)
        format.setStencilBufferSize(8)
        context = QOpenGLContext()
        context.setFormat(format)
        context.setShareContext(shareContext)
        context.create()

        self.size = size
        self.context = context

        # Create offscreen surface with initialized format
        self._surface = surface = QOffscreenSurface()
        surface.setFormat(context.format())
        surface.create()

        # Set up quick rendering
        self._control = control = QQuickRenderControl()
        self._window = window = QQuickWindow(control)
        self._engine = engine = QQmlEngine()
        if not engine.incubationController():
            engine.setIncubationController(window.incubationController())

        # Don't polish/sync/render immediately for better performance, use a timer
        self._renderTimer = renderTimer = QTimer()
        renderTimer.setSingleShot(True)
        renderTimer.setInterval(5)
        renderTimer.timeout.connect(self._onRenderTimer)
        self._syncTimer = syncTimer = QTimer()
        syncTimer.setSingleShot(True)
        syncTimer.setInterval(5)
        syncTimer.timeout.connect(self._onSyncTimer)
        syncTimer.destroyed.connect(self._onSyncTimerDestroyed)

        # Request to create frame buffer
        window.sceneGraphInitialized.connect(self._onSceneGraphInitialized)
        # Request to release frame buffer
        window.sceneGraphInvalidated.connect(self._onSceneGraphInvalidated)
        # Only render is needed
        control.renderRequested.connect(self._onRenderRequested)
        # Polish, sync & render
        control.sceneChanged.connect(self._onSceneChanged)

        self.initialized = True

        # Load QML component
        self._component = component = QQmlComponent(self._engine, self.qmlUrl)
        if component.isLoading():
            component.statusChanged.connect(self._onComponentStatusChanged)
        else:
            self._attachRootItem()
예제 #10
0
class HomeView(View):
    def __init__(self, engine):
        super().__init__(engine)

        self.component = QQmlComponent(self.engine)
        self.component.loadUrl('src/views/qml/components/PreviewCard.qml')
        self.projects_list = self.root.findChild(QQuickItem, 'projects')
        self.project_to_remove = None
        self.load_projects()

    def load_projects(self):
        """ Loads existing projets to ui
        """
        projects = project_controller.get_projects()

        for project in projects:
            self.add_project(project)

    def add_project(self, project):
        """ Adds a project entry to ui

            Args:
                project (Project): Project model
        """

        item = self.component.create()
        item.setProperty('project_id', project.project_id)
        item.setProperty('name', project.name)
        item.setProperty(
            'modified',
            f'Last modified: {self.timestamp_to_date(project.last_modified)}')
        item.setObjectName(project.project_id)
        item.setParentItem(self.projects_list)
        item.setParent(self.projects_list)

    def timestamp_to_date(self, timestamp):
        """ Converts a ISO 8601 date to datetime object

        Args:
            timestamp (string): ISO 8601 date representation

        Returns:
            datetime: Created datetime object
        """

        return dateutil.parser.isoparse(timestamp).strftime('%m-%d-%Y %H:%M')

    @Slot(str, str, str)
    def create_project_clicked(self, name, path, template_name):
        """ Callback to create project

        Args:
            name (string): Name that user entered
            path (string): Path that user entered
            template_name (string): Template name
        """

        try:
            project = project_controller.create_project(
                name, path, template_name)
            self.add_project(project)
        except InvalidValueError as err:
            self.show_error(get_literal('project_creation_failed'), str(err))
        except DirectoryNotEmptyError:
            self.show_error(get_literal('project_creation_failed'),
                            get_literal('dir_not_empty'))
        except ProjectExistsError:
            self.show_error(get_literal('project_creation_failed'),
                            get_literal('projects_already_exists'))
        except PermissionError:
            self.show_error(get_literal('project_creation_failed'),
                            get_literal('permission_denied'))

    @Slot(result=str)
    def get_default_path(self):
        """ Returns default project path to ui

        Returns:
            string: Default path
        """
        return config.get_value('default_project_path')

    @Slot(str)
    def request_project_removal(self, project_id):
        """ Called when user would like to remove a project.
            Shows a confirmation dialog to the user.

            Args:
                project_id (string): Id of the project to remove
        """
        self.project_to_remove = project_id
        project = project_controller.get_project_by_id(project_id)
        if not project:
            return

        child = self.root.findChild(QObject, 'confirmRemovalDialog')
        child.setProperty('visible', True)

        child.setProperty('text',
                          f'Do you want to remove project {project.name}?')

    @Slot(result=str)
    def remove_confirmed(self):
        """ Called when user has confirmed project removal dialog.

            Returns:
                string: Id of the project to remove
        """
        project_controller.remove_project(self.project_to_remove)

        child = self.root.findChild(QQuickItem, self.project_to_remove)
        child.deleteLater()

        return self.project_to_remove

    @Slot()
    def load_templates(self):
        """ Fetches all templates and returns a list of their names.

            Returns:
                string: list of names of the templates
        """
        templates = template_controller.get_template_names()

        dropdown = self.root.findChild(QObject, 'templateDropdown')
        dropdown.set_model([''] + templates)