Exemple #1
0
class LoginWin(QtCore.QObject):
    def __init__(self, state, app):
        QtCore.QObject.__init__(self)
        self.state = state
        self.app = app

        # Create the QML user interface.
        self.login_win = QQuickView()
        self.login_win.setTitle(self.tr("Xiami Login"))
        self.login_win.setSource(QUrl('login.qml'))
        self.login_win.setResizeMode(QQuickView.SizeRootObjectToView)
        self.login_win.show()

        # Connect signals
        self.root_obj = self.login_win.rootObject()
        self.root_obj.loginClicked.connect(self.login_clicked)
        self.root_obj.exitClicked.connect(self.exit_clicked)

    def set_state(self, msg):
        self.root_obj.setStatus(msg)

    def exit_clicked(self):
        sys.exit(0)

    def login_clicked(self, username, password):
        code = self.root_obj.getVerificationCode()
        if code != "":
            try:
                login.login_with_code(self.state, self.key, code)
            except Exception as e:
                self.set_state(e.message)
                self.root_obj.hideCode()
                return
            self.ok()
        else:
            try:
                ret = login.login(self.state, username, password)
            except Exception as e:
                self.set_state(e.message)
                return
            if not ret[0]:
                with open(login.img_path, 'wb') as imgf:
                    imgf.write(ret[2])
                self.set_state(self.tr("Please enter verification code"))
                self.root_obj.setVerificationImage("file://%s"
                                                   % login.img_path)
                self.key = ret[1]
            else:
                self.ok()

    def ok(self):
        self.login_win.close()
        self.app.auth_ok()
Exemple #2
0
    def __init__(self):
        super(QmlStartPage, self).__init__()
        box = QVBoxLayout(self)
        box.setContentsMargins(0, 0, 0, 0)
        # View
        view = QQuickView()
        view.setSource(QUrl.fromLocalFile(PATH_QML))
        view.setResizeMode(QQuickView.SizeRootObjectToView)
        # Root object
        self._root = view.rootObject()

        widget_container = QWidget.createWindowContainer(view)
        box.addWidget(widget_container)

        self._root.animationFinished.connect(self._on_animation_finished)
class TabletShortcuts(QGuiApplication):
    def __init__(self, argv):
        QGuiApplication.__init__(self, argv)

        self.view = QQuickView()

        self.bus = QDBusConnection.sessionBus()
        self.server = MyDBUSServer(self)
        self.bus.registerObject("/app", self.server)
        self.bus.registerService("sevanteri.TabletShortcuts")

        self.view.setTitle("TabletShortcuts")
        self.view.setResizeMode(QQuickView.SizeRootObjectToView)
        self.view.setSource(QUrl('main.qml'))

        self.root = self.view.rootObject()
        self.showView()

        self.root.runCommand.connect(self.run)
        self.root.hideView.connect(self.view.hide)

        self.view.engine().quit.connect(self.quit)

    def run(self, cmd):
        return Popen(shlex.split(cmd))

    def quit(self):
        self.exit()

    def showView(self):
        if self.view.isVisible():
            self.view.hide()
        else:
            # width, height = TabletShortcuts.getScreenGeometry()

            # self.view.setGeometry(1, 1, width, height)
            self.view.show()

    def getScreenGeometry():
        output = Popen("xrandr | grep 'current'", shell=True, stdout=PIPE)\
            .communicate()[0].decode('UTF-8')

        m = re.search('current.([0-9]+).x.([0-9]+)', output)
        width = int(m.group(1))
        height = int(m.group(2))

        return (width, height)
Exemple #4
0
    def __init__(self):
        super(StartPage, self).__init__()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        view = QQuickView()
        qml = os.path.join(settings.QML_PATH, "StartPage.qml")
        view.setSource(QUrl.fromLocalFile(qml))
        view.setResizeMode(QQuickView.SizeRootObjectToView)
        widget = QWidget.createWindowContainer(view)
        vbox.addWidget(widget)

        self.__root = view.rootObject()

        # Connections
        self.__root.openDatabase.connect(self.__open_database)
        self.__root.newDatabase.connect(self.__new_database)
        self.__root.removeCurrent.connect(self.__remove_current)
    def __init__(self, parent=None):
        super(MessageError, self).__init__(parent,
                                           Qt.Dialog | Qt.FramelessWindowHint)
        self._parent = parent
        self.setModal(True)
        self.setFixedHeight(150)
        self.setFixedWidth(350)
        box = QVBoxLayout(self)
        box.setContentsMargins(0, 0, 0, 0)
        view = QQuickView()
        qml = os.path.join(settings.QML_PATH, "MessageError.qml")
        view.setSource(QUrl.fromLocalFile(qml))
        view.setResizeMode(QQuickView.SizeRootObjectToView)
        self.widget = QWidget.createWindowContainer(view)
        box.addWidget(self.widget)

        self._root = view.rootObject()
        self._root.close.connect(self.close)
Exemple #6
0
def main():
    app = QApplication(sys.argv)

    # Register the Python type.
    # qmlRegisterType(Hal.Component, 'Hal', 1, 0, 'Component')
    # qmlRegisterType(Hal.Pin, 'Hal', 1, 0, 'Pin')
    qmlRegisterType(Stat.Stat, 'LinuxCNC', 1, 0, 'Stat')
    qmlRegisterType(Axis.Axis, 'LinuxCNC', 1, 0, 'Axis')
    qmlRegisterType(Command.Command, 'LinuxCNC', 1, 0, 'Command')
    qmlRegisterType(ErrorChannel.ErrorChannel, 'LinuxCNC', 1, 0, 'ErrorChannel')

    quickview = QQuickView()

    quickview.setSource(QUrl('gui/qml/main.qml'))
    quickview.showFullScreen()

    quickview.engine().quit.connect(app.quit)

    app.exec_()
def run_app():
    app = QGuiApplication(sys.argv)
    app.setApplicationName("Worship Prototype")

    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.setSource(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__), 'main.qml')))
    view.show()

    root = view.rootObject()
    preview = DefaultScreen()
    preview.wire_to_gui(root, 'previewScreen')
    preview.show_background(VideoBackground(os.path.join(os.path.dirname(__file__), '../echo.mp4')))
    # preview_live = DefaultScreen()
    # live = DefaultScreen()
    modules = [
        LyricsModule(SongsList(), root, preview),
    ]

    sys.exit(app.exec_())
Exemple #8
0
 def quickViewForQML(self, qmlFilename, transientParent=None):
   '''
   Create a QQuickView for qmlFilename.
   More robust: connects to error
   '''
   
   quickView = QQuickView()
   quickView.statusChanged.connect(self.onStatusChanged)
   
   qurl = resourceMgr.urlToQMLResource(resourceSubpath=qmlFilename)
   quickView.setSource(qurl)
   '''
   Show() the enclosing QWindow?
   But this means the window for e.g. the toolbar is visible separately?
   '''
   #quickView.show()
   print("Created QQuickView for:", qurl.path())
   if transientParent is not None:
     quickView.setTransientParent(transientParent)
   return quickView
Exemple #9
0
class MainWindow(QtCore.QObject):
    def __init__(self):
        QtCore.QObject.__init__(self)

        self._controller = Controller()

        self.view = QQuickView()

        full_path = os.path.realpath(__file__)
        folder = os.path.dirname(full_path)
        qml_file = os.path.join(folder, 'qml', 'App.qml')
        qml_qurl = QtCore.QUrl.fromLocalFile(qml_file)

        self.view.setSource(qml_qurl)

        # Add context properties to use this objects from qml
        rc = self.view.rootContext()
        rc.setContextProperty('controller', self._controller)

    def show(self):
        self.view.show()
Exemple #10
0
def main():
    app = QGuiApplication(sys.argv)
    app.setApplicationName('InfiniteCopy')

    openDataBase()

    view = QQuickView()

    clipboardItemModel = ClipboardItemModel()
    clipboardItemModel.create()

    filterProxyModel = QSortFilterProxyModel()
    filterProxyModel.setSourceModel(clipboardItemModel)

    clipboard = Clipboard()
    clipboard.setFormats([
        mimeText,
        mimeHtml,
        mimePng,
        mimeSvg
        ])
    clipboard.changed.connect(clipboardItemModel.addItem)

    engine = view.engine()

    imageProvider = ClipboardItemModelImageProvider(clipboardItemModel)
    engine.addImageProvider("items", imageProvider)

    context = view.rootContext()
    context.setContextProperty('clipboardItemModel', clipboardItemModel)
    context.setContextProperty('clipboardItemModelFilterProxy', filterProxyModel)
    context.setContextProperty('clipboard', clipboard)

    view.setSource(QUrl.fromLocalFile('qml/MainWindow.qml'))
    view.setGeometry(100, 100, 400, 240)
    view.show()

    engine.quit.connect(QGuiApplication.quit)

    return app.exec_()
Exemple #11
0
def run():
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    app = QGuiApplication(sys.argv)

    view = QQuickView()
    view.setTitle('Hot reloading demo')

    qml_engine = view.rootContext().engine()
    qml_engine.addImportPath(lib_dir_path)

    notifier = HotReloadNotifier(demo_dir_path, qml_engine, parent=app)
    view.rootContext().setContextProperty('hotReloadNotifier', notifier)

    qml_url = QUrl.fromLocalFile(os.path.join(demo_dir_path, 'Demo.qml'))
    view.setSource(qml_url)

    view.show()
    exit_code = app.exec_()

    # notifier.stop()  # seems like this is not needed
    sys.exit(exit_code)
        painter.setRenderHints(QPainter.Antialiasing, True)

        rect = QRectF(0, 0, self.width(), self.height()).adjusted(1, 1, -1, -1)
        painter.drawPie(rect, 90 * 16, 290 * 16)

    @pyqtSlot()
    def clearChart(self):
        self.color = QColor(Qt.transparent)
        self.update()

        self.chartCleared.emit()


if __name__ == '__main__':
    import os
    import sys

    app = QGuiApplication(sys.argv)

    qmlRegisterType(PieChart, "Charts", 1, 0, "PieChart")

    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.setSource(
        QUrl.fromLocalFile(
            os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         'app.qml')))
    view.show()

    sys.exit(app.exec_())
Exemple #13
0
##
#############################################################################


import sys
import os.path

from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView

# Access the shared module.
sys.path.insert(1,
        os.path.join(
                os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                'shared'))
import shared_rc

import canvas_rc


app = QGuiApplication(sys.argv)

view = QQuickView()
view.engine().quit.connect(app.quit)

view.setSource(QUrl('qrc:///canvas/canvas.qml'))
view.show()

sys.exit(app.exec_())
        painter.setRenderHints(QPainter.Antialiasing, True)

        rect = QRectF(0, 0, self.width(), self.height()).adjusted(1, 1, -1, -1)
        painter.drawPie(rect, 90 * 16, 290 * 16)

    @pyqtSlot()
    def clearChart(self):
        self.color = QColor(Qt.transparent)
        self.update()

        self.chartCleared.emit()  # 发射信号


if __name__ == '__main__':
    import os
    import sys

    app = QGuiApplication(sys.argv)

    qmlRegisterType(PieChart, "Charts", 1, 0, "PieChart")

    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.setSource(
        QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__),
                                        'test5.qml')))

    # view.setSource(QUrl('test5.qml'))
    view.show()

    sys.exit(app.exec_())
        # engine = QQmlApplicationEngine()

        # # guifile = QUrl('TemperatureApp.qml')
        # # component = QQmlComponent(engine, guifile)
        # # rec = component.create()

        # # print(rec)
        # # rec.parentItem().show()
        # engine.load(QUrl('TemperatureApp.qml'))
        # rec = engine.rootObjects()[0]
        # rec.window().show()
        # # win = engine.rootObjects()[0]
        # # win.show()

        view = QQuickView()
        view.setSource(QUrl('TemperatureApp.qml'))

        # Show the Label
        view.show()

        root = view.rootObject()

        text_temp = root.findChild(QQuickItem, "txtTemp")

        light_switch = root.findChild(QQuickItem, "swtLight")
        light_switch.clicked.connect(light_switch_event)

        tsensor_thread = TemperatureSensor()

        tsensor_thread.start()
        ret = app.exec_()
            return animal.type()

        if role == self.SizeRole:
            return animal.size()

        return QVariant()

    def roleNames(self):
        return self._roles


if __name__ == '__main__':
    import sys

    app = QGuiApplication(sys.argv)

    model = AnimalModel()
    model.addAnimal(Animal("Wolf", "Medium"))
    model.addAnimal(Animal("Polar bear", "Large"))
    model.addAnimal(Animal("Quoll", "Small"))

    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    ctxt = view.rootContext()
    ctxt.setContextProperty('myModel', model)

    view.setSource(QUrl('qrc:view.qml'))
    view.show()

    sys.exit(app.exec_())
Exemple #17
0
## $QT_END_LICENSE$
##
#############################################################################

import sys
import os.path

from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView

# Access the shared module.
sys.path.insert(
    1,
    os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                 "shared"),
)
import shared_rc

import animation_rc

app = QGuiApplication(sys.argv)

view = QQuickView()
view.engine().quit.connect(app.quit)

view.setSource(QUrl("qrc:///animation/animation.qml"))
view.show()

sys.exit(app.exec_())
Exemple #18
0
            invt = 1 - t

            pos = invt * invt * invt * self._p1 \
                    + 3 * invt * invt * t * self._p2 \
                    + 3 * invt * t * t * self._p3 \
                    + t * t * t * self._p4

            vertices[i].set(pos.x() * w, pos.y() * h)

        self._root_node.markDirty(QSGNode.DirtyGeometry)

        return self._root_node


if __name__ == '__main__':
    import sys

    app = QGuiApplication(sys.argv)

    qmlRegisterType(BezierCurve, "CustomGeometry", 1, 0, "BezierCurve")

    view = QQuickView()
    format = view.format()
    format.setSamples(16)
    view.setFormat(format)

    view.setSource(QUrl('qrc:///scenegraph/customgeometry/main.qml'))
    view.show()

    sys.exit(app.exec_())
Exemple #19
0
def buildandsave(league_name, exit_on_save=True):
    try:
        agent = Agent(reactor)
        league_user = User().get_by_role(league_name, keys.entity_twitter)
        print 'league_user:'******'team:',
                                  query_filter={
                                      'twitter__null': False,
                                      'twitter_id__null': False
                                  }):
            d = agent.request(
                "HEAD",
                str('http://' + t[keys.entity_site] + '/tw/' +
                    t[keys.entity_twitter_id] + '/avatar_large.png'))
            d.addCallback(add_redirect, t, teams, 'large')
            deferreds_team.append(d)
        yield defer.DeferredList(deferreds_team)

        players = []
        deferreds_small = []
        for p in Entity().query_2(league__eq=sys.argv[1],
                                  profile__beginswith='http:',
                                  query_filter={
                                      'twitter__null': False,
                                      'twitter_id__null': False
                                  },
                                  limit=300):
            d = agent.request(
                "HEAD",
                str('http://' + p[keys.entity_site] + '/tw/' +
                    p[keys.entity_twitter_id] + '/avatar_small.png'))
            d.addCallback(add_redirect, p, players, 'small')
            deferreds_small.append(d)
        yield defer.DeferredList(deferreds_small)
        print 'players length:', len(players)

        view = QQuickView()
        view.setSource(QUrl('qml/render/league_twitter_bg.qml'))
        view.setWidth(1500)
        view.setHeight(500)
        view.show()

        try:
            view.rootObject().setProperty(
                'bgcolor', '#' + league_user[keys.entity_colors][0])
        except:
            view.rootObject().setProperty('bgcolor', '#000000')
        view.rootObject().setProperty('league', league)
        view.rootObject().setProperty('players', players)
        view.rootObject().setProperty('teams', teams)

        yield task.deferLater(reactor, 30, screenshot, view, league_user)
        if exit_on_save:
            print 'exit on save'
            reactor.callLater(0, reactor.stop)
        else:
            print 'done'
    except Exception as e:
        print 'build and save exception:', e
Exemple #20
0
from PyQt5.QtQuick import QQuickView
from PyQt5.QtWidgets import QApplication

from qtypes.argv import ArgParser
from qtypes.vend import Vend


if __name__ == '__main__':
    # Reminder to self, see link for why we avoid a 'main' function here
    # http://pyqt.sourceforge.net/Docs/PyQt5/pyqt4_differences.html#object-destruction-on-exit

    app = QApplication(sys.argv)
    print(sys.version)
    print("InvoiceIt")
    root = os.path.dirname(__file__)

    app.setApplicationName("InvoiceIt")
    app.setApplicationDisplayName("InvoiceIt")
    app.setApplicationVersion("0.1")

    view = QQuickView()
    qmlRegisterType(ArgParser, "ArgV", 1, 0, "ArgParser")
    qmlRegisterType(Vend, "Vend", 1, 0, "Vendor")

    f = QUrl.fromLocalFile(join(root, 'qml', 'main.qml'))
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.setSource(f)
    view.show()

    sys.exit(app.exec_())
Exemple #21
0
def run_charts():
    print 'run charts'
    gsi = Tweet().describe()['Table']['GlobalSecondaryIndexes']
    oil = [g for g in gsi
           if g['IndexName'] == Tweet.index_league][0]['ProvisionedThroughput']
    oil = {
        Tweet.index_league: {
            'read': oil['ReadCapacityUnits'],
            'write': oil['WriteCapacityUnits']
        }
    }
    nil = copy.deepcopy(oil)
    nil[Tweet.index_league]['read'] = 200
    oil[Tweet.index_league]['read'] = 20
    try:
        print 'increate throughput:', nil
        Tweet().update_global_secondary_index(global_indexes=nil)
    except Exception as e:
        print 'increase exception:', e
    yield task.deferLater(reactor, 15, defer.succeed, True)
    for u in User().scan(role__contains='.com', twitter_apps__null=False):
        try:
            site = u[user_keys.user_role]
            chart_tweet = tweets.chart_tweet(u, 'Last 24 Hours')
            print 'chart tweet:', chart_tweet
            yield task.deferLater(reactor, 1, defer.succeed, True)
            print 'site:', site
            if not u[keys.entity_description]:
                u[keys.entity_description] = 'placeholder'
                u.partial_save()

            yesterday = int(time.time()) - (24 * 60 * 60)
            yesterday = str(yesterday * 1000)

            curator = User().get_by_role(site, keys.entity_twitter)
            charts = []

            categories = list(curator[user_keys.user_site_leagues])
            for c in categories:
                #tc = SocialBeta().query_count(SocialBeta.index_social_ts_received, league__eq=c, social_ts_received__gt=yesterday, query_filter={'social_act__eq': 'tweet'})
                tweet_filter = {
                    'known_retweet__null': True,
                    'unknown_retweet__null': True,
                    '_ts_ms__gt': yesterday
                }

                tc = Tweet().query_count(index=Tweet.index_league,
                                         league__eq=c,
                                         query_filter=tweet_filter,
                                         scan_index_forward=False)

                known_retweet_filter = {
                    'known_retweet__null': False,
                    '_ts_ms__gt': yesterday
                }
                krc = Tweet().query_count(index=Tweet.index_league,
                                          league__eq=c,
                                          query_filter=known_retweet_filter,
                                          scan_index_forward=False)

                unknown_retweet_filter = {
                    'unknown_retweet__null': False,
                    '_ts_ms__gt': yesterday
                }
                urc = Tweet().query_count(index=Tweet.index_league,
                                          league__eq=c,
                                          query_filter=unknown_retweet_filter,
                                          scan_index_forward=False)

                conversion_filter = {
                    'known_conversation__null': False,
                    '_ts_ms__gt': yesterday
                }
                cc = Tweet().query_count(index=Tweet.index_league,
                                         league__eq=c,
                                         query_filter=conversion_filter,
                                         scan_index_forward=False)
                ce = {c: (tc, krc, urc, cc)}
                print ce
                charts.append(ce)

            charts.sort(key=lambda x: x[x.keys()[0]][0])

            tweets_list = [t[t.keys()[0]][0] for t in charts]
            known_retweets_list = [t[t.keys()[0]][1] for t in charts]
            unknown_retweets_list = [t[t.keys()[0]][2] for t in charts]
            conversations_list = [t[t.keys()[0]][3] for t in charts]
            categories = [t.keys()[0] for t in charts]

            height = 200 + (40 * len(categories))

            view = QQuickView()
            view.setSource(QUrl('qml/render/chart_daily.qml'))
            view.setWidth(800)
            view.setHeight(height)

            view.rootObject().setProperty('categories', categories)
            view.rootObject().setProperty('_height', height)
            view.rootObject().setProperty(
                'title', 'Tweets/Retweets/Conversations - ' + site)
            view.rootObject().setProperty('description',
                                          u[keys.entity_description])
            view.rootObject().setProperty('conversations', conversations_list)
            view.rootObject().setProperty('retweets', known_retweets_list)
            view.rootObject().setProperty('unknown_retweets',
                                          unknown_retweets_list)
            view.rootObject().setProperty('tweets', tweets_list)

            view.show()
            yield task.deferLater(reactor, 5, defer.succeed, True)
            img = view.grabWindow()
            chart_location = '/home/ubuntu/Desktop/' + site + '.png'
            res = img.save(chart_location)
            print 'save result:', res
            yield task.deferLater(reactor, 5, defer.succeed, True)
            restful.post_tweet(u, u, chart_tweet, chart_location)
            yield task.deferLater(reactor, 15, defer.succeed, True)
            os.remove(chart_location)
            view.deleteLater()

        except Exception as e:
            print 'chart exception:', e
    try:
        print 'decreate throughput:', oil
        Tweet().update_global_secondary_index(global_indexes=oil)
    except Exception as e:
        print 'descrease exception:', e
    yield task.deferLater(reactor, 15, defer.succeed, True)
    reactor.callLater(0, reactor.stop)
Exemple #22
0
 def loadMainView(self):
     view = QQuickView()
     view.rootContext().setContextProperty("base", self)
     view.setSource(QUrl("main.qml"))
     self.mainWindow = self
     r = view.rootObject()
#Sample Python File
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView

if __name__ == '__main__':
    import os
    import sys

    app = QGuiApplication(sys.argv)

    view = QQuickView()
    view.setWidth(500)
    view.setHeight(500)
    view.setTitle('Hello PyQt')
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.setSource(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__),'main.qml')))

    view.show()
    qml_rectangle = view.rootObject()

    sys.exit(app.exec_())
Exemple #24
0
# -*- coding: utf-8 -*-
import os, sys, re

from PyQt5.QtNetwork import *

from fboinsgrenderer import *
from textureinsgnode_rc import *

from PyQt5.QtGui import QSurfaceFormat
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import (QVariant, QUrl, QDir, QSortFilterProxyModel, pyqtProperty, QSize,
    Q_ENUMS, QObject, QRegExp, QAbstractItemModel, pyqtSignal, Qt, QModelIndex, QByteArray)
from PyQt5.QtQml import (QQmlApplicationEngine, QQmlEngine, QQmlFileSelector, qmlRegisterType,
    QQmlParserStatus, QJSValue)
from PyQt5.QtQuick import QQuickView, QQuickItem, QQuickWindow

if __name__ == '__main__':
    app = QApplication(sys.argv)

    qmlRegisterType(FboInSGRenderer, "SceneGraphRendering", 1, 0, "Renderer")
    widgetWindow = QQuickView()
    widgetWindow.setResizeMode(QQuickView.SizeRootObjectToView)
    widgetWindow.setSource(QUrl("qrc:///main.qml"))
    widgetWindow.show()

    sys.exit(app.exec_())
Exemple #25
0
if __name__ == '__main__':
    import sys
    from Curves import BezierCurve
    from Generators import JsonGenerator

    app = QGuiApplication(sys.argv)

    qmlRegisterType(ConsoleOutput, 'PyConsole', 1, 0, 'PyConsole')
    qmlRegisterType(BezierCurve, 'Curves', 1, 0, 'BezierCurve')
    qmlRegisterType(JsonGenerator, 'Generators', 1, 0, 'JsonGenerator')

    view = QQuickView()
    context = view.rootContext()

    view.engine().quit.connect(app.quit)
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.setSource(
        QUrl.fromLocalFile('../view/visionai.qml')
    )
    view.show()

    for error in view.errors():
        print(error.toString())

    status = app.exec_()

    for error in view.errors():
        print(error.toString())

    sys.exit(status)
Exemple #26
0
#!/usr/bin/env python3

import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView

# Main Function
if __name__ == '__main__':
    # Create main app
    myApp = QApplication(sys.argv)
    # Create a label and set its properties
    appLabel = QQuickView()
    appLabel.setSource(QUrl('2.qml'))

    # Show the Label
    appLabel.show()

    # Execute the Application and Exit
    myApp.exec_()
    sys.exit()
Exemple #27
0
component = QQmlComponent(engine)
component.loadUrl(QUrl('WeatherDash.qml'))

# Create the QML user interface.  Auto creates its own engine
view = QQuickView()

engine2 = view.engine
# Does not run
#engine2.quit.connect(app.quit)

#view.setSource(QUrl('PyTest.qml'))
# To Satisfy cool-retro-term needs
view.rootContext().setContextProperty('devicePixelRatio', app.devicePixelRatio())

view.setSource(QUrl('WeatherDash.qml'))
#view.setResizeMode(QDeclarativeView.SizeRootObjectToView)
view.setGeometry(100, 100, 750, 480)
# ala https://pythonspot.com/pyqt5-colors/
view.setColor(QColor(0, 30, 0))

view.show()

is_full_screen = False

# technique lifted from https://stackoverflow.com/questions/19131084/pyqt5-qml-signal-to-python-slot
# and augmented from https://stackoverflow.com/questions/30586983/how-to-close-pyqt5-program-from-qml
# could refine with https://stackoverflow.com/questions/24111717/how-to-bind-buttons-in-qt-quick-to-python-pyqt-5
# not 100% ideal, but adequate and interesting
def on_quit():
    app.quit()
Exemple #28
0
    def __init__(self):
        super(MyMain,self).__init__()
        self.btsearch = Search()


    @pyqtSlot(str,int,result = QVariant)
    def add_items(self,parm,index):
        bt_thread = Thread(target = self.thread_add_items,args = (parm,index,))
        bt_thread.start()

    @pyqtSlot(str,int,result = QVariant)
    def thread_add_items(self,parm,index):
        result = self.btsearch.search(parm)
        self.signal_add_items.emit(QVariant(result),index)


if __name__ == '__main__':
    path = 'main.qml'
    app = QApplication([])
    view = QQuickView()
    con = MyMain()
    context = view.rootContext()
    context.setContextProperty("con",con)
    view.engine().quit.connect(app.quit)
    view.setSource(QUrl(path))
    view.show()
    root = view.rootObject()
    con.signal_add_items.connect(root.slot_add_items)
    app.exec()

Exemple #29
0
## (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
## HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

############################################################

import sys
import os.path

from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView

op = input("Digite v ou t [para Varredura ou Toque]: ")
if op == 'V' or op == 'v':
    import gera_jogo_varredura
    gera_jogo_varredura.main(arqEntrada = "bateria.json", arqSaida = "bateria.qml")
else:
    import gera_jogo
    gera_jogo.main(arqEntrada = "bateria.json", arqSaida = "bateria.qml")
    
app = QGuiApplication(sys.argv)

view = QQuickView()
view.engine().quit.connect(app.quit)

view.setSource(QUrl('bateria.qml'))
view.show()

sys.exit(app.exec_())
Exemple #30
0
from PyQt5.QtGui import QGuiApplication

if __name__ == '__main__':

    #get our data
    url = "http://country.io/names.json"
    response = urllib.request.urlopen(url)
    data = json.loads(response.read().decode('utf-8'))

    #Format and sort the data
    data_list = list(data.values())
    data_list.sort()

    #Set up the application window
    app = QGuiApplication(sys.argv)
    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)

    #Expose the list to the Qml code
    my_model = QStringListModel()
    my_model.setStringList(data_list)
    view.rootContext().setContextProperty("myModel", my_model)

    #Load the QML file
    qml_file = os.path.join(os.path.dirname(__file__), "test.ui.qml")
    view.setSource(QUrl.fromLocalFile(os.path.abspath(qml_file)))

    #Show the window
    if view.status() == QQuickView.Error:
        sys.exit(-1)
    view.show()
Exemple #31
0

class WorkThread(QThread):
    # 定义一个信号
    trigger = pyqtSignal(str)

    def __int__(self):
        # 初始化函数,默认
        super(WorkThread, self).__init__()

    def run(self):
        # time.sleep(2)
        self.trigger.emit("ok")
        HandleWork.lc.handle()


if __name__ == "__main__":
    path = os.getcwd() + "\content\MainControl.qml"
    app = QGuiApplication(sys.argv)
    viewer = QQuickView()
    con = MainPanel()
    context = viewer.rootContext()
    context.setContextProperty("con", con)
    viewer.engine().quit.connect(app.quit)
    viewer.setResizeMode(QQuickView.SizeRootObjectToView)
    viewer.setSource(QUrl.fromLocalFile(path))
    rootObject = viewer.rootObject()
    subprocess.Popen("python server.py")
    viewer.show()
    app.exec_()
Exemple #32
0
from _002_2d_triangle.triangle import TriangleUnderlay

if __name__ == '__main__':
    # Not working in Ubuntu 16.04, result in 1282 error for simple calling like glViewport(...)
    if platform.uname().system == 'Darwin':
        f = QSurfaceFormat()
        f.setVersion(4, 1)
        f.setDepthBufferSize(1)  # fix depth buffer error
        f.setStencilBufferSize(1)  # fix stencil buffer error

        # If CoreProfile is used, all the other QML rendering will fail, because they only use 2.1
        f.setProfile(QSurfaceFormat.CompatibilityProfile)
        QSurfaceFormat.setDefaultFormat(f)

    qmlRegisterType(TriangleUnderlay, 'OpenGLUnderQml', 1, 0,
                    'TriangleUnderlay')

    app = QGuiApplication(sys.argv)

    view = QQuickView()
    view.setFormat(f)
    view.setPersistentSceneGraph(True)
    view.setPersistentOpenGLContext(True)
    view.setResizeMode(QQuickView.SizeRootObjectToView
                       )  # Set for the object to resize correctly
    view.setSource(QUrl('TriangleWindow.qml'))
    view.show()

    app.exec()
Exemple #33
0
# -*-coding: utf-8-*-
import sys, os, random
from PyQt5.QtCore import QUrl, QTimer, QVariant, QPoint
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView

# app = QGuiApplication(sys.argv)
app = QApplication(sys.argv)

view = QQuickView()
# view.setResizeMode(QQuickView.SizeRootObjectToView)
view.engine().quit.connect(app.quit)

# ImageBrowser
# view.setSource(QUrl("./ImageBrowser/ImageBrowser.qml"))
# for i in range(5):
#     view.rootObject().addImage("../resources/ImageBrowser/{}.jpg".format(i+1))

# NotJustLineChart
view.setTitle("NotJustLineChart")
view.setSource(QUrl("NChart/ElementLayer.qml"))
# view.setResizeMode(QQuickView.SizeRootObjectToView)

# view.setSource(QUrl("./LineChart/ZoomSlider.qml"))

view.show()
sys.exit(app.exec_())
Exemple #34
0
from _004_3d_loading_model_and_rotating.object import ModelUnderlay
import platform

if __name__ == '__main__':
	# Not working in Ubuntu 16.04, result in 1282 error for simple calling like glViewport(...)
	# TODO

	if platform.uname().system == 'Darwin':
		f = QSurfaceFormat()
		f.setVersion(4, 1)
		f.setDepthBufferSize(1)  # fix depth buffer error
		f.setStencilBufferSize(1)  # fix stencil buffer error

		# If CoreProfile is used, all the other QML rendering will fail, because they only use 2.1
		f.setProfile(QSurfaceFormat.CompatibilityProfile)
		QSurfaceFormat.setDefaultFormat(f)

	qmlRegisterType(ModelUnderlay, 'OpenGLUnderQml', 1, 0, 'ModelUnderlay')

	app = QGuiApplication(sys.argv)

	view = QQuickView()
	# view.setFormat(f)
	view.setPersistentSceneGraph(True)
	view.setPersistentOpenGLContext(True)
	view.setResizeMode(QQuickView.SizeRootObjectToView)  # Set for the object to resize correctly
	view.setSource(QUrl('ModelWindow.qml'))
	view.show()

	app.exec()
        return self._name

    @name.setter
    def name(self, name):
        self._name = name

    def __init__(self, parent=None):
        super(PieChart, self).__init__(parent)

        self._name = ''


if __name__ == '__main__':
    import os
    import sys

    app = QGuiApplication(sys.argv)

    qmlRegisterType(PieChart, "Charts", 1, 0, "PieChart")
    qmlRegisterType(PieSlice, "Charts", 1, 0, "PieSlice")

    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.setSource(
            QUrl.fromLocalFile(
                    os.path.join(os.path.dirname(os.path.abspath(__file__)),
                            'app.qml')))
    view.show()

    sys.exit(app.exec_())
Exemple #36
0
    def initData(self):
        objs = []
        for i in range(10):
            objdict = {
                'name': 'qwe%s' % i,
                'count': i,
                'cover': '/home/djf/jjk/',
                'songs': {'song': '1111'}
            }
            obj = self.dataTye(**objdict)
            objs.append(obj)

        self.data = objs


if __name__ == '__main__':
    import sys

    app = QGuiApplication(sys.argv)

    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    ctxt = view.rootContext()
    myListModel = ListModel(QmlArtistObject)
    ctxt.setContextProperty('myListModel', myListModel)

    view.setSource(QUrl('ListShow.qml'))
    view.show()

    sys.exit(app.exec_())
Exemple #37
0
class PhotoBoothGUI(QObject):
    def run(self):
        # Create main app
        self.myApp = QApplication(sys.argv)
        # Create a label and set its properties
        self.appLabel = QQuickView()
        #self.appLabel.setSource(QUrl('loading.qml'))

        # Show the Label
        self.appLabel.show()

        # Initialize PhotoBoothEngine.
        self.pbengine = PhotoBoothEngine()

        self.pbengine.on_change_url.connect(self.update_url_signal)
        self.pbengine.on_connect_signal.connect(self.connect_signal)

        self.pbengine.change_qml(0)
        self.pbengine.connect_state(0)

        print("UPDATE")
        #self.pbengine.on_status.connect(self.appLabel.rootObject().status)
        #self.pbengine.on_update_filter_preview.connect(self.appLabel.rootObject().updateImageFilterPreview)

        self.appLabel.rootContext().setContextProperty('pbengine',
                                                       self.pbengine)

        self.setup_text_status_fly_component()

        self.pbengine.start_state_thread(0)

        # Execute the Application and Exit
        self.myApp.exec_()
        sys.exit()

    def setup_text_status_fly_component(self):
        # Create a component factory and load the QML script.
        print("Hello")
        self.component = QQmlComponent(self.appLabel.engine())
        self.component.loadUrl(QUrl('qml/TextStatusFly.qml'))

        print("Hello2")
        self.statuswidget = self.component.create(self.appLabel.rootContext())

        print("Hello3")
        self.statuswidget.setParentItem(self.appLabel.rootObject())
        self.statuswidget.setParent(self.appLabel.rootObject())

        print("Hello4")
        #statuswidget.setProperty("targetX", 100)
        self.statuswidget.setProperty("objectName", "textStatusBar")

        print("Hello5")
        self.appLabel.rootContext().setContextProperty('textStatusBar',
                                                       self.statuswidget)

        self.statuswidget.setProperty("parentSet", True)

    def update_url_signal(self, url):
        print(" ** Updating URL: %s" % url)

        #self.pbengine.on_change_url.disconnect()
        #self.pbengine.on_connect_signal.disconnect()

        self.appLabel.rootContext().setContextProperty('textStatusBar', None)
        self.appLabel.setSource(QUrl())
        self.appLabel.engine().clearComponentCache()
        self.appLabel.setSource(QUrl(url))
        self.setup_text_status_fly_component()
        self.appLabel.show()

        # Reconnect
        #self.pbengine.on_change_url.connect(self.update_url_signal)
        #self.pbengine.on_connect_signal.connect(self.connect_signal)

    def connect_signal(self, signal, target):
        print(" ** Binding signal %s to target %s!" % (str(signal), target))
        print(" ** (getattr(self.appLabel, target) = %s)" %
              (str(getattr(self.appLabel.rootObject(), target))))
        signal.connect(getattr(self.appLabel.rootObject(), target))
Exemple #38
0
## $QT_END_LICENSE$
##
#############################################################################

import sys
import os.path

from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView

# Access the shared module.
sys.path.insert(
    1,
    os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                 "shared"),
)
import shared_rc

import canvas_rc

app = QGuiApplication(sys.argv)

view = QQuickView()
view.engine().quit.connect(app.quit)

view.setSource(QUrl("qrc:///canvas/canvas.qml"))
view.show()

sys.exit(app.exec_())
        self._color = color


if __name__ == "__main__":
    import os
    import sys

    # This is necessary to avoid a possible crash when running from another
    # directory by ensuring the compiled version of the embedded QML file
    # doesn't get mixed up with another of the same name.
    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    app = QGuiApplication(sys.argv)

    dataList = [
        DataObject("Item 1", "red"),
        DataObject("Item 2", "green"),
        DataObject("Item 3", "blue"),
        DataObject("Item 4", "yellow"),
    ]

    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    ctxt = view.rootContext()
    ctxt.setContextProperty("myModel", dataList)

    view.setSource(QUrl("qrc:view.qml"))
    view.show()

    sys.exit(app.exec_())
Exemple #40
0
    client.subscribe("4Box")  #subscribe
    print("Box Engine 4 subscribed ")

    client.subscribe("WindDirection")  #subscribe
    client.subscribe("WindSpeed")  #subscribe
    client.subscribe("WindBox")  #subscribe
    print("Box Wind subscribed ")

    client.publish("MainControl", "active")  #publish

    ## QT5 GUI
    print("Graphical User Interface ")
    app = QGuiApplication(sys.argv)

    view = QQuickView()
    view.setSource(QUrl('main.qml'))

    mqttvalue = MQTTValue()

    timer = QTimer()
    timer.start(10)  ##Update screen every 10 miliseconds

    context = view.rootContext()
    context.setContextProperty("mqttvalue", mqttvalue)

    root = view.rootObject()
    timer.timeout.connect(root.updateValue)  ##Call function update in GUI QML

    engine = QQmlApplicationEngine(app)
    engine.quit.connect(app.quit)  ## Quit Button Respon
Exemple #41
0
    def __init__(self, parent=None):
        super(Trace, self).__init__(parent)
        self.freq = 1.0

    def get_data(self):
        max = 256
        data = list(map(lambda x: int(127 + 127 * math.sin( 2.0 * math.pi * self.freq * x / max)), range(0,max)))
        self.freq *= 1.01
        self.new_data.emit(data)

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

# Create the QML user interface.
view = QQuickView()
view.setSource(QUrl('test.qml'))
#view.setResizeMode(QDeclarativeView.SizeRootObjectToView)
view.showFullScreen()


scope = ScopeInterface()
scope.new_data.connect(view.rootObject().newData)

scope.initialize()
scope.capture()

sys.exit(app.exec_())

scope.stop()
Exemple #42
0
# -*- coding: utf-8 -*-
#from PyQt5.QtGui import QApplication
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QVariant, QUrl, QDir
from PyQt5.QtQml import QQmlApplicationEngine, QQmlEngine
from PyQt5.QtQuick import QQuickView, QQuickItem, QQuickWindow




if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    viewer = QQuickView()
    viewer.setSource(QUrl("main.qml"))

    viewer.setTitle("Material Demo QML")
    viewer.engine().quit.connect(app.quit)
    viewer.resize(500, 500)
    viewer.setResizeMode(QQuickView.SizeRootObjectToView)
    viewer.show()

    sys.exit(app.exec_())
Exemple #43
0
#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtQml import qmlRegisterType
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView

from dpcs.speaker import Speaker
from dpcs.qmlmodel import Database, Category, Symbol

app = QGuiApplication(sys.argv)

qmlRegisterType(Speaker, 'DPCS', 1, 0, 'Speaker')
qmlRegisterType(Database, 'DPCS', 1, 0, 'Database')
qmlRegisterType(Category, 'DPCS', 1, 0, 'Category')
qmlRegisterType(Symbol, 'DPCS', 1, 0, 'Symbol')

view = QQuickView()
view.engine().quit.connect(app.quit)

view.setSource(QUrl('main.qml'))
view.show()

sys.exit(app.exec_())
Exemple #44
0
if __name__ == '__main__':
    #===========================================================================
    # import os
    # import sys
    # app = QGuiApplication(sys.argv)
    # engine = QQmlApplicationEngine()
    # context = engine.rootContext()
    # game = Game()
    # context.setContextProperty('loginCh', game)
    # qml_filename = os.path.join('qml/main.qml')
    # engine.load(qml_filename)
    # sys.exit(app.exec_())
    #===========================================================================

    myApp = QApplication(sys.argv)
    # Create a label and set its properties
    appLabel = QQuickView()
    game = Game()
    user = User()
    appLabel.rootContext().setContextProperty('loginCh', game)
    appLabel.rootContext().setContextProperty('user', user)
    appLabel.setSource(QUrl('qml/Loginw.qml'))

    # Show the Label
    appLabel.show()

    # Execute the Application and Exit
    myApp.exec_()
    sys.exit()
Exemple #45
0
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
## $QT_END_LICENSE$
##
#############################################################################

import sys
import os.path

from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView

# Access the shared module.
sys.path.insert(
    1,
    os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                 'shared'))
import shared_rc

import canvas_rc

app = QGuiApplication(sys.argv)

view = QQuickView()
view.engine().quit.connect(app.quit)

view.setSource(QUrl('qrc:///canvas/canvas.qml'))
view.show()

sys.exit(app.exec_())
Exemple #46
0
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView
from PyQt5.QtCore import QUrl

if __name__ == "__main__":
    app = QApplication(sys.argv)
    view = QQuickView()
    view.setSource(QUrl("main.qml"))
    view.setGeometry(300, 300, 300, 200)
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.show()
    sys.exit(app.exec_())
Exemple #47
0
#
#     win = engine.rootObjects()[0]
#     win.show()
#     sys.exit(app.exec_())

if __name__ == '__main__':

    _file = r"choice_cnx.csv"
    _qml = r'main.qml'

    # Prints QML errors
    def handleStatusChange(status):
        if status == QQuickView.Error:
            errors = view.errors()
            if errors:
                print(errors[0].description())

    myApp = QApplication(sys.argv)
    qmlRegisterType(TestModel, 'TestModel', 1, 0, 'TestModel')

    view = QQuickView()
    view.rootContext().setContextProperty('fromPython', "text de la nasa")
    view.statusChanged.connect(handleStatusChange)

    view.setSource(QUrl(_qml))

    try:
        sys.exit(myApp.exec_())
    except:
        print("Exiting")
Exemple #48
0
import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView

from PyQt5.QtQml import QQmlComponent, QQmlEngine

from engine import PhotoBoothEngine

# Main Function
if __name__ == '__main__':
    # Create main app
    myApp = QApplication(sys.argv)
    # Create a label and set its properties
    appLabel = QQuickView()
    appLabel.setSource(QUrl('main.qml'))
    #appLabel.load(QUrl('main2.qml'))

    # Show the Label
    appLabel.show()
    
    # Create a QML engine.
    engine = QQmlEngine()
    
    # Initialize PhotoBoothEngine.
    pbengine = PhotoBoothEngine()
    pbengine.on_status.connect(appLabel.rootObject().status)
    pbengine.on_update_filter_preview.connect(appLabel.rootObject().updateImageFilterPreview)
    
    appLabel.rootContext().setContextProperty('pbengine', pbengine)
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from os.path import (
    join,
    dirname,
)

from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView

app = QGuiApplication(sys.argv)
view = QQuickView()

view.engine().quit.connect(app.quit)

url = QUrl(join(dirname(__file__), 'ControllerComponent/ControllerComponent.qml'))
view.setSource(url)
view.show()
sys.exit(app.exec_())
Exemple #50
0
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
## $QT_END_LICENSE$
##
#############################################################################

import sys
import os.path

from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView

# Access the shared module.
sys.path.insert(
    1,
    os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                 'shared'))
import shared_rc

import animation_rc

app = QGuiApplication(sys.argv)

view = QQuickView()
view.engine().quit.connect(app.quit)

view.setSource(QUrl('qrc:///animation/animation.qml'))
view.show()

sys.exit(app.exec_())
Exemple #51
0
import sys

from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView

if __name__ == '__main__':
    app = QGuiApplication(sys.argv)

    view = QQuickView()
    view.setSource(QUrl('SimpleRect.qml'))
    view.setResizeMode(QQuickView.SizeRootObjectToView
                       )  # Set for the object to resize correctly

    view.show()

    app.exec()
Exemple #52
0
        

def sniff_data(qroot):
    cap = pyshark.FileCapture('D:\\4.pcapng')
    for p in cap:
        if 'MODBUS' in p:
            if p['IP'].src == '192.168.0.103':
                packet_windturbine_1(p, qroot)
        else:
            continue

if __name__ == '__main__':
    
    path = 'main.qml'   
    app = QGuiApplication([])
    
    view = QQuickView()
    
    view.engine().quit.connect(app.quit)   
    view.setSource(QUrl(path))             
    view.show()

    context = view.rootContext()
    rootobj = view.rootObject()

    sniff_thread = Thread(target=sniff_data, args=(rootobj,))
    sniff_thread.setDaemon(True)
    sniff_thread.start()

    app.exec_()                         
Exemple #53
0
	client.subscribe("2pulse_spc")#subscribe
	print("Box Engine 2 subscribed ")
	
	client.subscribe("WindDirection")#subscribe
	client.subscribe("WindSpeed")#subscribe
	client.subscribe("WindBox")#subscribe
	print("Box Wind subscribed ")
	
	client.publish("MainControl", "active")#publish

	## QT5 GUI
	print("Graphical User Interface ")
	app = QGuiApplication(sys.argv)

	view = QQuickView()
	view.setSource(QUrl('dashboard.qml'))

	mqttvalue = MQTTValue()

	timer = QTimer()
	timer.start(10) ##Update screen every 10 miliseconds

	context = view.rootContext()
	context.setContextProperty("mqttvalue", mqttvalue)

	root = view.rootObject()
	timer.timeout.connect(root.updateValue) ##Call function update in GUI QML

	engine = QQmlApplicationEngine(app) 
	engine.quit.connect(app.quit) ## Quit Button Respon
		
            return animal.type()

        if role == self.SizeRole:
            return animal.size()

        return QVariant()

    def roleNames(self):
        return self._roles


if __name__ == '__main__':
    import sys

    app = QGuiApplication(sys.argv)

    model = AnimalModel()
    model.addAnimal(Animal("Wolf", "Medium"))
    model.addAnimal(Animal("Polar bear", "Large"))
    model.addAnimal(Animal("Quoll", "Small"))

    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    ctxt = view.rootContext()
    ctxt.setContextProperty('myModel', model)

    view.setSource(QUrl('qrc:view.qml'))
    view.show()

    sys.exit(app.exec_())
Exemple #55
0
class P2CQMLApplication(QGuiApplication):
    def __init__(self, list_of_str):
        super().__init__(list_of_str)
        self._current_category = None
        self._current_torrent = None
        self._current_torrent_info = None
        self._status_timer = QTimer(self)
        self._movies_thread = None
        self._search_thread = None

    def run_view(self):
        self._view = QQuickView()
        self._view.engine().addImportPath("qml")
        self._rctx = self._view.rootContext()
        self._view.setResizeMode(QQuickView.SizeRootObjectToView)

        # set context variables
        self.categories = []
        self._rctx.setContextProperty("categoriesModel", self.categories)
        self.tiles = []
        self.torrents = []
        self._rctx.setContextProperty("moviesModel", self.tiles)
        self._set_loading(False)
        self._view.setSource(QUrl('qrc:/qml.qml'))
        self._view.showFullScreen()
#        self._view.show()

    def connect_daemon(self, daemon: P2CDaemon):
        self._daemon = daemon
        self._set_categories()
        self._connect_signals()

    def play(self, movie: Movie):
        self._set_movie_status("Ready to play!")
        self._set_media(movie)
        self._daemon.play(movie)
        self._set_additional_media_info()

    def buffer(self, movie: Movie):
        seconds = self._current_torrent.get_seconds_to_buffer()
        info = "just started"
        if seconds:
            if seconds < 15:
                info = "just a moment"
            else:
                # rount to minutes
                minutes = int(seconds / 60) + 1
                if minutes == 1:
                    info = "1 minute"
                else:
                    info = "{} minutes".format(minutes)
        self._set_movie_status("Buffering... ({})".format(info))
        self._daemon.buffer(movie)
        self._set_additional_media_info()

    def wait_for_metadata(self):
        self._set_movie_status("Getting metadata...")
        if self._current_torrent:
            self._set_additional_media_info(self._current_torrent.name)

    def select_movie(self, torrent: Torrent) -> Movie:
        movies = torrent.get_movies()
        if len(movies) == 0:
            return
        # TODO: show dialog with movie selecting instead of doing it automatically
        return max(movies, key=lambda x: x.size)

    def update_status(self):
        torrent = self._current_torrent
        if torrent:
            if (torrent.has_torrent_info()):
                movie = self.select_movie(torrent)
                if not movie:
                    self._set_movie_status(
                        "No movie in this torrent. Please, select another.")
                    return

                torrent.download_file(movie.path)
                self._set_duration(movie)
                if not self._daemon.is_playing(movie):
                    if (movie.can_play()):
                        #                        print(movie.get_subtitles())
                        self.play(movie)
                    else:
                        self.buffer(movie)

                ### DEBUG INFO
                text = "s: %s, num p: %s, rate: %s kbs, p_rate: %s kbs" % (
                    torrent.get_status()['state'],
                    torrent.get_status()['num_peers'],
                    int(torrent.get_status()['download_rate'] / 1024),
                    int(torrent.get_status()['download_payload_rate'] / 1024),
                )
                self._view.rootObject().setProperty("debugText", text)
                ### END DEBUG INFO

            else:
                self.wait_for_metadata()
        else:
            self.wait_for_metadata()

    def on_category_clicked(self, index):
        # clear list
        self._set_torrents([], loading=True)

        category = self._daemon.get_categories()[index]
        self._current_category = category

        if self._current_category:
            self._search_thread = None
            self._movies_thread = SetMoviesThread(self._current_category)
            self._movies_thread.start()
            self._movies_thread.got_movies.connect(self._threaded_set_torrents)

    def on_movie_clicked(self, index):
        self._view.rootObject().setProperty("isMovieScene", True)

        torrent_ui = self.torrents[index]
        self._current_torrent = self._daemon.get_torrent(torrent_ui)
        self._current_torrent_info = torrent_ui
        self.update_status()

    def on_search(self, query):
        if len(query) < 3:
            return
            # clear list
        self._set_torrents([], loading=True)

        self._movies_thread = None
        self._search_thread = SearchThread(query, self._daemon.search)
        self._search_thread.start()
        self._search_thread.got_movies.connect(self._threaded_set_torrents)

    def on_exit(self):
        self.quit()

    def _connect_signals(self):
        self._view.rootObject().categoryClicked.connect(
            self.on_category_clicked)
        self._view.rootObject().movieClicked.connect(self.on_movie_clicked)
        self._view.rootObject().movieClicked.connect(self.on_movie_clicked)
        self._view.rootObject().searchQuery.connect(self.on_search)
        self._view.rootObject().exitAction.connect(self.on_exit)
        self._status_timer.timeout.connect(self.update_status)
        self._status_timer.start(500)

    def _set_movie_status(self, text):
        self._rctx.setContextProperty("movieStatus", text)

    def _set_media(self, movie: Movie):
        file_name = movie.get_target_path()
        self._rctx.setContextProperty("movieSource",
                                      QUrl.fromLocalFile(file_name))

    def _set_additional_media_info(self, title=None):
        self._rctx.setContextProperty(
            "title", title or self._current_torrent_info.title
            or self._current_torrent_info.label)
        self._rctx.setContextProperty(
            "poster",
            self._current_torrent_info.poster if self._current_torrent_info
            and self._current_torrent_info.poster else '')

    def _set_categories(self):
        data = []
        for category in self._daemon.get_categories():
            data.append(Tile(category.label, category.service.name))
        self._rctx.setContextProperty("categoriesModel", data)
        self.categories = data

    def _threaded_set_torrents(self, data, thread):
        # if latest action
        if thread == self._movies_thread or thread == self._search_thread:
            self._set_torrents(data)

    def _set_torrents(self, data, loading=False):
        # only existing tiles
        for (tile, torrent_info) in zip(self.tiles, data[:len(self.tiles)]):
            if torrent_info.title:
                tile.name = torrent_info.title
                tile.source = torrent_info.label
            else:
                tile.name = torrent_info.label
                tile.source = None
            tile.poster = torrent_info.poster
            tile.description = torrent_info.description

        if len(data) != len(self.tiles):
            for torrent_info in data[len(self.tiles):]:
                if torrent_info.title:
                    tile = Tile(torrent_info.title, torrent_info.label,
                                torrent_info.poster, torrent_info.description)
                else:
                    tile = Tile(torrent_info.label, None, torrent_info.poster,
                                torrent_info.description)
                self.tiles.append(tile)

            self._rctx.setContextProperty("moviesModel", self.tiles)
        self.torrents = data
        self._set_loading(loading)

    def _set_loading(self, loading):
        self._rctx.setContextProperty("loadingMask", loading)

    def _set_duration(self, movie: Movie):
        tdelta = movie.get_movie_duration()
        if tdelta:
            self._view.rootObject().setProperty("movieDuration",
                                                tdelta.seconds * 1000)
Exemple #56
0
## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
## $QT_END_LICENSE$
##
#############################################################################

import sys
import os.path

from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView
#animation 폴더의 animation_rc 와 shared 폴더의 shared_rc를 import해온다.
from shared_rc import *
from animation_rc import *

if len(sys.argv) is 2:# 실행 옵션으로 파이썬도움말 절대경로 제공시
    os.chdir(sys.argv[1])


app = QGuiApplication(sys.argv)
view = QQuickView()
view.engine().quit.connect(app.quit)
view.setSource(QUrl('animation.qml'))
view.show()
sys.exit(app.exec_())
Exemple #57
0
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView
import myQML

app = QGuiApplication(sys.argv)



print('-----------------------------------------------------------------------')


qmlFile = 'main.qml'

#qmlFile = "qrc:data/"


view = QQuickView()
view.setResizeMode(QQuickView.SizeRootObjectToView)
view.engine().quit.connect(app.quit)

engine = view.engine()
view.setSource(QUrl(qmlFile)) # putting at the end didn't solve referenceError 'This is supposed to solve all referenceErrors



view.show()
sys.exit(app.exec_())