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()
def main():
    print("start")
    app = QApplication(sys.argv)
    qmlRegisterType(Person, 'People', 1, 0, 'Person')
    v = QQuickView(QUrl("testFindChild.qml"))
    qmlRoot = v.rootObject()
    assert isinstance(qmlRoot, QQuickItem)
    assert isinstance(qmlRoot, QObject)
    dumpQMLComponents(qmlRoot)
    result = qmlRoot.findChild(Person, "person")
    assert result is not None
    
    sys.exit(app.exec_())
Exemple #3
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 #5
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)
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 __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()

        self.cur_alt = int(self.abs_alt) + int_alt
        self.newAlt.emit(self.cur_alt)

    def signal_new_batt_stat(self):
        print("new batt_stat is: " + str(self.batt_stat))
        pct = self.batt_stat / 15.0 * 100
        pct_str = "{0:.2f}".format(pct)
        rem_time = pct / 100 * 5
        time_str = "{0:.2f}".format(rem_time)
        self.newBattStat.emit(pct_str, time_str)

    def signal_state_changed(self, state):
        print("state changed to: " + state + "\n")
        self.stateChanged.emit(state)


app = QApplication([])
view = QQuickView()
view.setWidth(1200)
view.setHeight(720)
view.setTitle('Telemetry Tracker')
view.setResizeMode(QQuickView.SizeRootObjectToView)
url = QUrl('interface.qml')
gui = Gui(sys.argv[1])
gui.connect_signals()
view.rootContext().setContextProperty('gui', gui)
view.setSource(url)
view.show()
qml_window = view.rootObject()
app.exec_()
Exemple #10
0
from PyQt5.QtCore import QUrl

avi_property = []
for e in Entity().query_2(index=Entity.index_team_profile,
                          team__eq=sys.argv[1],
                          query_filter={'twitter__null': False}):
    print e._data
    avi_property.append(e._data)

print avi_property

view = QQuickView()
view.setSource(QUrl('qml/render/avi_team.qml'))
view.setWidth(590)
view.setHeight(360)
view.rootObject().setProperty('avis',
                              json.dumps(avi_property, cls=fixed.SetEncoder))
view.show()
print view.rootObject()


def screenshot():
    img = view.grabWindow()
    res = img.save('/home/ubuntu/Desktop/test.png')
    #res = img.save('/home/ubuntu/Desktop/avi_' + sys.argv[2] + '.png')
    print 'save result:', res


#img = view.rootObject().grabToImage()
#print img
from twisted.internet import task, reactor
task.deferLater(reactor, 10,
#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 #12
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 #13
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 #14
0
    def create_node(self, node):
        # Creates new node from source QML and puts it inside of main window
        qml_node = QQuickView(QUrl(self._qml_dir + '/shapes/' +
                                   self.shapes[node.shape] + '.qml'),
                              self._main)

        workspace = self._main.rootObject().findChild(QQuickItem, "workspace")

        # Sets all properties
        qml_node.rootObject().setProperty("parent", workspace)
        qml_node.rootObject().setProperty("objectId", str(node.id))
        qml_node.rootObject().setProperty("background",
                                          str(node.background))
        qml_node.rootObject().setProperty("width", str(node.width))
        qml_node.rootObject().setProperty("height", str(node.height))
        qml_node.rootObject().setProperty("text", str(node.text.text))
        qml_node.rootObject().setProperty("textFont", str(node.text.font))
        qml_node.rootObject().setProperty("textSize", str(node.text.size))
        qml_node.rootObject().setProperty("textColor", str(node.text.color))

        # Sets drag boundaries
        qml_node.rootObject().setProperty("workspaceWidth",
                                          str(workspace.property("width")))
        qml_node.rootObject().setProperty("workspaceHeight",
                                          str(workspace.property("height")))

        # Signal connection
        qml_node.rootObject().node_delete.connect(
            self._controller.node_delete)
        qml_node.rootObject().node_text_changed.connect(
            self._controller.node_text_changed)
        qml_node.rootObject().node_position_changed.connect(
            self._controller.node_position_changed)
        qml_node.rootObject().node_connect.connect(
            self._controller.node_connect)
        qml_node.rootObject().node_focus.connect(
            self._controller.node_focus)
        if node.shape == 2:
            qml_node.rootObject().node_image_loaded.connect(
                self._controller.node_image_loaded)

        # Position to mouse click
        qml_node.rootObject().setX(node.x - node.width / 2)
        qml_node.rootObject().setY(node.y - node.height / 2)
        qml_node.rootObject().setZ(2)

        return qml_node
Exemple #15
0
        bus = dbus.SessionBus()
        session = bus.get_object('org.qoverview.config',
                                 '/org/qoverview/config')
        config = dbus.Interface(session, 'org.qoverview.config.iface')

    except:
        print(
            'config-server is (probably) not running! (Unable to connect to it via DBUS)'
        )
        print(
            'Start it and try again. The command is "qoverview-config-server"')
        sys.exit(1)

    app = QGuiApplication(sys.argv)

    qmlview = QQuickView()
    qmlview.setSource(QUrl('ui.qml'))

    qmlview.setResizeMode(qmlview.SizeRootObjectToView)

    root = qmlview.rootObject()
    context = qmlview.rootContext()

    interface = PythonQMLInterface(view=qmlview)

    context.setContextProperty('Python', interface)

    qmlview.showFullScreen()

    app.exec_()
Exemple #16
0
def qt_avatar(avi=None, prefix='/tmp'):
    print 'new avatar:', avi[keys.entity_twitter], 'twitter id:', avi[
        keys.entity_twitter_id]
    meta = {}
    curator = User().get_curator(avi[keys.entity_league])
    previous = None
    try:
        avis = s3.get_twitter_media(avi, 'large')
        count = str(len(avis))
        current = fixed.key_url(avis[0])
        previous = fixed.key_url(avis[1])
    except Exception as e:
        print e
    print current, 'count:', count, 'previous:', previous
    bgcolor = 'black'
    local_font = 'http://socialcss.com/Roboto-Regular.ttf?raw=true'
    site = curator[user_keys.user_role]

    friends = []
    try:
        ls = ProfileTwitter().profile_last(avi[keys.entity_twitter_id])
        meta.update(ls._data)
        print 'has recent:', fixed.days_since(ls,
                                              time_keys.ts_add) if ls else None
        if ls[ProfileTwitter.profile_background_color]:
            bgcolor = '#' + ls[ProfileTwitter.profile_background_color]
            print 'colors background:', bgcolor, 'link profile:', ls[
                'profile_link_color']
        for f in list(ls[twitter_keys.league_follows(
                avi[keys.entity_league])].intersection(
                    ls[twitter_keys.league_mutual(avi[keys.entity_league])])):
            friends.append(f)
        print 'friend:', friends
    except Exception as e:
        print 'avatar exception:', e

    meta.update(avi)

    view = QQuickView()
    view.setSource(QUrl('qml/render/avi_update.qml'))
    view.show()

    view.setWidth(590)
    view.rootObject().setProperty('current', current)
    if previous:
        view.rootObject().setProperty('previous', previous)
    view.rootObject().setProperty('bgcolor', bgcolor)
    view.rootObject().setProperty('font', local_font)
    view.rootObject().setProperty('site', site)
    view.rootObject().setProperty('count', count)
    view.rootObject().setProperty('league', avi[keys.entity_league])
    view.rootObject().setProperty('twitter', avi[keys.entity_twitter])
    if friends:
        view.setHeight(380)
        view.rootObject().setProperty('friends', json.dumps(friends))
    else:
        view.setHeight(280)

    local_file_name = prefix + '/avi_update_' + avi[
        keys.entity_twitter] + '.png'
    print 'local_file_name:', local_file_name

    def tick():
        try:
            upload_png = avi[keys.entity_league] + '/tweet/' + str(
                int(time.time())) + '.png'
            img = view.grabWindow()
            print 'img:', img, local_file_name, img.isNull()
            render_res = img.save(local_file_name)
            print 'render_res:', render_res, 'file name:', upload_png, 'tweet:', avi
            if render_res and avi and twitter_keys.message_tweet in avi:
                b = s3.bucket_straight(curator['role'])
                s3.save_s3(b, upload_png, None, local_file_name, 'image/png',
                           'public-read', meta)
                if avi:

                    avi[twitter_keys.
                        message_pic] = 'http://' + b.name + '/' + upload_png
                    print 'append to tweet:', avi[
                        twitter_keys.message_tweet], 'url:', avi[
                            twitter_keys.message_pic]
                    TweetQueue().createMessage(avi)
            else:
                print 'skip publish'
        except Exception as e:
            print 'tick exception:', e
        reactor.callLater(0, reactor.stop)

    QTimer.singleShot(15000, tick)
    oglFormat.setVersion(3, 3)
    view.setFormat(oglFormat)

    # define our viewport
    class HelloGLWorld(GlFboViewportI):
        def __init__(self):
            self.frameCount = 0

        def Cleanup(self):
            pass

        def Draw(self, fboName: int, viewSize: QPoint):
            if self.frameCount % 100 > 50:
                glClearBufferfv(GL_COLOR, 0, (1, .5, .5, 1))
            else:
                glClearBufferfv(GL_COLOR, 0, (.5, 1, .5, 1))

            self.frameCount = self.frameCount + 1

    ourGlViewport = HelloGLWorld()

    # set our viewport into the loaded qml,
    # see: Qt 5.5.1 Reference Documentation > Qt QML > Interacting with QML Objects from C++
    theAdapterInstance = view.rootObject().findChild(
        QquickItemFromGlFboViewportAdapter,
        "helloOurViewportAdapter")  #type: QquickItemFromGlFboViewportAdapter
    theAdapterInstance.SetViewport(ourGlViewport)

    # let the result shown
    view.show()
    sys.exit(app.exec())
Exemple #18
0
from PyQt5.QtCore import QUrl, QObject, pyqtSlot, pyqtSignal
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView
import mnistMethod

path = 'mainWindow.qml'
app = QGuiApplication([])
view = QQuickView()
view.engine().quit.connect(app.quit)
view.setHeight(700)
view.setWidth(1200)
view.setSource(QUrl(path))
view.show()

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

context.setContextProperty("mnistHandler", mnistMethod.mnistHandler)

app.exec_()
Exemple #19
0
class Example(QWidget):
    @pyqtSlot(QVariant)
    def sendImgToGallery(self, aword):
        print(aword)
        #o = self.view.findChild(QObject, 'textEdit')
        #print(o)
        print("kek")

    def getTagsString(self, tagsArray):
        tagsString = ""
        for tag in tagsArray:
            tagsString += tag+", "
        return tagsString

    def buttonClicked(self):
        file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
        if (file):
            QMetaObject.invokeMethod(
                self.view.rootObject(), "clear")
            #QMetaObject.invokeMethod(
             #   self.view.rootObject(), "showBusyIndicator")
        self.startProcessing(file)

    def selectSortDirPath(self):
        file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
        if (file):
            self.sortDirPath = file
            QMetaObject.invokeMethod(self.view.rootObject(), "setSortDitPathTextField", Q_ARG(QVariant, file))
            
    def getAllImagePathFromDir(self, directoryPath):
        fileNameArray = []
        for (dirpath, dirnames, filenames) in walk(directoryPath):
            fileNameArray.extend(filenames)
            break
        for idx in range(len(fileNameArray)):
            fileNameArray[idx] = directoryPath+"/"+fileNameArray[idx]
        return fileNameArray

    def getImageInformationFromKhiena(self, fileNameArray):
        imgInfoArray = []
        print(fileNameArray)
        for idx in range(len(fileNameArray)):
            imgInfoArray.append(apiKhiena.imgSearch(fileNameArray[idx]))
            if (idx % 2 == 0):
                time.sleep(10)

        print("============")
        # print(imgInfoArray)
        return imgInfoArray

    def startProcessing(self, pathToDir):
        fileNameArray = self.getAllImagePathFromDir(pathToDir)
        fileImageInfoArray = self.getImageInformationFromKhiena(fileNameArray)
        imgCounter = 0
        for imageInfo in fileImageInfoArray:
            if (not imageInfo["source"]):
                continue
            imgInfo = imgUrlGetter.getImgInfoFromUrl(imageInfo["source"])
            completeSourceText = '<a href="' + \
                imageInfo["source"]+'"+>'+imageInfo["source"]+'</a>'
            print("img Path: "+imgInfo["imgLink"])
            stringTags = self.getTagsString(imgInfo["tags"])
            if (imageInfo["rating"]==0):
                stringTags += "safe, "
            elif  (imageInfo["rating"]==1):
                stringTags += "questionable, "
            elif  (imageInfo["rating"]==2):
                stringTags += "explicit, "
            
            print("RATING: ",imageInfo["rating"])

            stringTags += "artist:"+imageInfo["artist"]
            similarity = imageInfo["similarity"]
            colorRowRect = "#f2ca7d"
            if similarity < 90:
                colorRowRect = "#f04747"

            btnName = "sendBtnName"+str(imgCounter)
            value = {"similarity": similarity,
                     "source": completeSourceText,
                     "localImgPath": imageInfo["localImgPath"],
                     "remoteImgPath": imgInfo["imgLink"],
                     "tags": stringTags,
                     "colorRowRect": colorRowRect,
                     "sendBtnName":btnName}
            # print(value)
            imgCounter+=1
            QMetaObject.invokeMethod(
                self.view.rootObject(), "append", Q_ARG(QVariant, value))
            
            #print(btnName)
            #sendButton = self.view.findChild(QObject, "sendBtnName0")
            #print(sendButton)
            #sendButton.clicked.connect(self.sendImgToGallery)

        #QMetaObject.invokeMethod(
        #        self.view.rootObject(), "hideBusyIndicator")

    def on_qml_mouse_clicked(self):
        print('mouse clicked')

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        self.view = QQuickView()
        self.view.setSource(QUrl('mainWin.qml'))
        self.view.rootContext().setContextProperty("ex",self)
        self.sortDirPath = ""
        openFolderButton = self.view.findChild(QObject, "toolButton")
        openFolderButton.clicked.connect(self.buttonClicked)

        selectSortDirButton = self.view.findChild(QObject, "selectSortDirButton")
        selectSortDirButton.clicked.connect(self.selectSortDirPath)

        child = self.view.findChild(QObject, "limgListModel")

        imageInfo = {"idshnik": 4,
                     'similarity': 80.859408,
                     'title': "Dragons' Journeyby Selianth",
                     'source': 'https://furrynetwork.com/artwork/1382822',

                     'artist': 'selianth',
                     'rating': 0,
                     'localImgPath': '/home/ /драконы-неразр-тест/425808117_107442_11461217378126189089.jpg'}
        colorRowRect = "#f2ca7d"
        value1 = {'similarity': 97.144509,
                  'source': '<a href="https://furrynetwork.com/artwork/341709">https://furrynetwork.com/artwork/341709</a>',
                  'localImgPath': '/home/ /драконы-неразр-тест/246938919_136836_11381943016272256370.jpg',
                  'remoteImgPath': 'https://d3gz42uwgl1r1y.cloudfront.net/ko/kodar/submission/2016/02/1dac4b544380d5874a518047f24b4eb2.jpg',
                  'tags': "artist:Kodar, any, dragon, fantasy, western",
                  "colorRowRect": colorRowRect,
                  "sendBtnName":"sendBtn0"}

        value = {"similarity": imageInfo["similarity"],
                 "source": imageInfo["source"],
                 "localImgPath": imageInfo["localImgPath"],
                 }
        QMetaObject.invokeMethod(
            self.view.rootObject(), "append", Q_ARG(QVariant, value1))
        self.view.show()
Exemple #20
0
    # 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)

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

    print("Hello2")
    asdf = component.create(appLabel.rootContext())

    print("Hello3")
    asdf.setParentItem(appLabel.rootObject())
Exemple #21
0
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()

def on_toggle_fullscreen():
    global is_full_screen
    if is_full_screen:
        view.show()
    else:
        view.showFullScreen()
    is_full_screen = not is_full_screen

weather_dash = view.rootObject()
weather_dash.quit.connect(on_quit)
weather_dash.toggleFullScreen.connect(on_toggle_fullscreen)

# may want to do this slightly differently, though I prefer QML doing the heavy lifting
# http://doc.qt.io/qt-5/qqmlcomponent.html
#weather_chart = view.findChild(Loader, "WeatherChart")

# this does work
#view.showFullScreen()

app.exec_()
Exemple #22
0
class View(object):

    shapes = ["rectangle", "ellipse", "image"]
    edgetypes = ["line", "curve"]

    def __init__(self):
        self._controller = Controller(self)
        self._gui = QGuiApplication(sys.argv)

        self._qml_dir = os.path.dirname(os.path.realpath(__file__))
        self._main = QQuickView()
        self._main.setResizeMode(QQuickView.SizeRootObjectToView)
        self._main.setSource(QUrl(self._qml_dir + '/main.qml'))

        self._main.rootObject().create_node.connect(
            self._controller.create_node)
        self._main.rootObject().mouse_position.connect(
            self._controller.mouse_position)
        self._main.rootObject().save.connect(
            self._controller.save)
        self._main.rootObject().load.connect(
            self._controller.load)
        self._main.rootObject().lose_focus.connect(
            self._controller.lose_focus)
        self._main.rootObject().node_color_sel.connect(
            self._controller.node_color_sel)
        self._main.rootObject().edge_color_sel.connect(
            self._controller.edge_color_sel)
        self._main.rootObject().workspace_height_changed.connect(
            self._controller.workspace_height_changed)
        self._main.rootObject().workspace_width_changed.connect(
            self._controller.workspace_width_changed)
        self._main.rootObject().edge_type_sel.connect(
            self._controller.edge_type_sel)
        self._main.rootObject().node_shape_sel.connect(
            self._controller.node_shape_sel)
        self._main.rootObject().clear_workspace.connect(
            self._controller.clear_workspace)
        self._main.rootObject().node_width_changed.connect(
            self._controller.node_width_changed)
        self._main.rootObject().node_height_changed.connect(
            self._controller.node_height_changed)
        self._main.rootObject().node_text_color_sel.connect(
            self._controller.node_text_color_sel)
        self._main.rootObject().node_text_size_changed.connect(
            self._controller.node_text_size_changed)
        self._main.rootObject().edge_thickness_changed.connect(
            self._controller.edge_thickness_changed)
        self._main.rootObject().show_edge_controls.connect(
            self._controller.show_edge_controls)
        self._main.rootObject().hide_edge_controls.connect(
            self._controller.hide_edge_controls)
        self._main.rootObject().exporting.connect(
            self._controller.exporting)
        self._main.setProperty(
            "width", self._controller.project.workspace_width)
        self._main.setProperty(
            "height", self._controller.project.workspace_height)
        self._main.show()

    def run(self):
        return self._gui.exec_()

    def create_node(self, node):
        # Creates new node from source QML and puts it inside of main window
        qml_node = QQuickView(QUrl(self._qml_dir + '/shapes/' +
                                   self.shapes[node.shape] + '.qml'),
                              self._main)

        workspace = self._main.rootObject().findChild(QQuickItem, "workspace")

        # Sets all properties
        qml_node.rootObject().setProperty("parent", workspace)
        qml_node.rootObject().setProperty("objectId", str(node.id))
        qml_node.rootObject().setProperty("background",
                                          str(node.background))
        qml_node.rootObject().setProperty("width", str(node.width))
        qml_node.rootObject().setProperty("height", str(node.height))
        qml_node.rootObject().setProperty("text", str(node.text.text))
        qml_node.rootObject().setProperty("textFont", str(node.text.font))
        qml_node.rootObject().setProperty("textSize", str(node.text.size))
        qml_node.rootObject().setProperty("textColor", str(node.text.color))

        # Sets drag boundaries
        qml_node.rootObject().setProperty("workspaceWidth",
                                          str(workspace.property("width")))
        qml_node.rootObject().setProperty("workspaceHeight",
                                          str(workspace.property("height")))

        # Signal connection
        qml_node.rootObject().node_delete.connect(
            self._controller.node_delete)
        qml_node.rootObject().node_text_changed.connect(
            self._controller.node_text_changed)
        qml_node.rootObject().node_position_changed.connect(
            self._controller.node_position_changed)
        qml_node.rootObject().node_connect.connect(
            self._controller.node_connect)
        qml_node.rootObject().node_focus.connect(
            self._controller.node_focus)
        if node.shape == 2:
            qml_node.rootObject().node_image_loaded.connect(
                self._controller.node_image_loaded)

        # Position to mouse click
        qml_node.rootObject().setX(node.x - node.width / 2)
        qml_node.rootObject().setY(node.y - node.height / 2)
        qml_node.rootObject().setZ(2)

        return qml_node

    def create_edge(self, edge, node1, node2):
        qml_edge = QQuickView(QUrl(self._qml_dir + '/edges/' +
                                   self.edgetypes[edge.type] + '.qml'),
                              self._main)
        workspace = self._main.rootObject().findChild(QQuickItem, "workspace")

        qml_edge.rootObject().setProperty("parent", workspace)
        qml_edge.rootObject().setProperty("objectId", str(edge.id))
        qml_edge.rootObject().setZ(1)

        qml_edge.rootObject().setProperty(
            "width", workspace.property("width"))
        qml_edge.rootObject().setProperty(
            "height", workspace.property("height"))

        qml_edge.rootObject().setProperty("ctrlX", str(edge.x))
        qml_edge.rootObject().setProperty("ctrlY", str(edge.y))
        qml_edge.rootObject().setProperty("startX", str(node1.x))
        qml_edge.rootObject().setProperty("startY", str(node1.y))
        qml_edge.rootObject().setProperty("endX", str(node2.x))
        qml_edge.rootObject().setProperty("endY", str(node2.y))
        qml_edge.rootObject().setProperty("color", str(edge.color))
        qml_edge.rootObject().setProperty("thickness", str(edge.thickness))
        qml_edge.rootObject().setProperty("spiked", str(edge.spiked))
        qml_edge.rootObject().setProperty("arrow", str(edge.arrow))

        # Sets drag boundaries
        qml_edge.rootObject().setProperty("workspaceWidth",
                                          str(workspace.property("width")))
        qml_edge.rootObject().setProperty("workspaceHeight",
                                          str(workspace.property("height")))

        # Signal connection
        qml_edge.rootObject().edge_delete.connect(
            self._controller.edge_delete)
        qml_edge.rootObject().edge_position_changed.connect(
            self._controller.edge_position_changed)
        qml_edge.rootObject().edge_focus.connect(
            self._controller.edge_focus)

        return qml_edge

    def node_update(self, node):
        pass
Exemple #23
0
    def create_edge(self, edge, node1, node2):
        qml_edge = QQuickView(QUrl(self._qml_dir + '/edges/' +
                                   self.edgetypes[edge.type] + '.qml'),
                              self._main)
        workspace = self._main.rootObject().findChild(QQuickItem, "workspace")

        qml_edge.rootObject().setProperty("parent", workspace)
        qml_edge.rootObject().setProperty("objectId", str(edge.id))
        qml_edge.rootObject().setZ(1)

        qml_edge.rootObject().setProperty(
            "width", workspace.property("width"))
        qml_edge.rootObject().setProperty(
            "height", workspace.property("height"))

        qml_edge.rootObject().setProperty("ctrlX", str(edge.x))
        qml_edge.rootObject().setProperty("ctrlY", str(edge.y))
        qml_edge.rootObject().setProperty("startX", str(node1.x))
        qml_edge.rootObject().setProperty("startY", str(node1.y))
        qml_edge.rootObject().setProperty("endX", str(node2.x))
        qml_edge.rootObject().setProperty("endY", str(node2.y))
        qml_edge.rootObject().setProperty("color", str(edge.color))
        qml_edge.rootObject().setProperty("thickness", str(edge.thickness))
        qml_edge.rootObject().setProperty("spiked", str(edge.spiked))
        qml_edge.rootObject().setProperty("arrow", str(edge.arrow))

        # Sets drag boundaries
        qml_edge.rootObject().setProperty("workspaceWidth",
                                          str(workspace.property("width")))
        qml_edge.rootObject().setProperty("workspaceHeight",
                                          str(workspace.property("height")))

        # Signal connection
        qml_edge.rootObject().edge_delete.connect(
            self._controller.edge_delete)
        qml_edge.rootObject().edge_position_changed.connect(
            self._controller.edge_position_changed)
        qml_edge.rootObject().edge_focus.connect(
            self._controller.edge_focus)

        return qml_edge
Exemple #24
0
    subscription = lc.subscribe("SIMULATOR", my_handler)


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 = 'main.qml'
    app = QApplication(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(path))
    rootObject = viewer.rootObject()
    viewer.show()
    app.exec_()
Exemple #25
0
    # 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)

    # Create a component factory and load the QML script.
    print("Hello")
    component = QQmlComponent(appLabel.engine())
    component.loadUrl(QUrl('TextStatusFly.qml'))
    
    print("Hello2")
    asdf = component.create(appLabel.rootContext())
    
    print("Hello3")
    asdf.setParentItem(appLabel.rootObject())
    asdf.setParent(appLabel.rootObject())
Exemple #26
0
class PluginsStore(QDialog):

    def __init__(self, parent=None):
        super(PluginsStore, self).__init__(parent, Qt.Dialog)
       # QDialog.__init__(self, parent, Qt.Dialog | Qt.FramelessWindowHint)
        self.setWindowTitle(self.tr("Plugins Store"))
        self.setMaximumSize(QSize(0, 0))

        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        self.view = QQuickView()
        self.view.setMinimumWidth(800)
        self.view.setMinimumHeight(600)
        self.view.setResizeMode(QQuickView.SizeRootObjectToView)
        self.view.setSource(ui_tools.get_qml_resource("PluginsStore.qml"))
        self.root = self.view.rootObject()
        vbox.addWidget(self.view)
        self._plugins = {}
        self._plugins_inflate = []
        self._plugins_by_tag = collections.defaultdict(list)
        self._plugins_by_author = collections.defaultdict(list)
        self._base_color = QColor("white")
        self._counter = 0
        self._counter_callback = None
        self._inflating_plugins = []
        self._categoryTags = True
        self._search = []
        self.status = None

        self.connect(self.root, SIGNAL("loadPluginsGrid()"),
                     self._load_by_name)
        self.connect(self.root, SIGNAL("close()"),
                     self.close)
        self.connect(self.root, SIGNAL("showPluginDetails(int)"),
                     self.show_plugin_details)
        self.connect(self.root, SIGNAL("loadTagsGrid()"),
                     self._load_tags_grid)
        self.connect(self.root, SIGNAL("loadAuthorGrid()"),
                     self._load_author_grid)
        self.connect(self.root, SIGNAL("search(QString)"),
                     self._load_search_results)
        self.connect(self.root, SIGNAL("loadPluginsForCategory(QString)"),
                     self._load_plugins_for_category)
        self.connect(self, SIGNAL("processCompleted(PyQt_PyObject)"),
                     self._process_complete)

        self.nenv = nenvironment.NenvEggSearcher()
        self.connect(self.nenv,
                     SIGNAL("searchCompleted(PyQt_PyObject)"),
                     self.callback)
        self.status = self.nenv.do_search()

    def _load_by_name(self):
        if self._plugins:
            self.root.showGridPlugins()
            for plugin in list(self._plugins.values()):
                self.root.addPlugin(plugin.identifier, plugin.name,
                                    plugin.summary, plugin.version)

    def _load_plugins_for_category(self, name):
        self.root.showGridPlugins()
        if self._categoryTags:
            for plugin in self._plugins_by_tag[name]:
                self.root.addPlugin(plugin.identifier, plugin.name,
                                    plugin.summary, plugin.version)
        else:
            for plugin in self._plugins_by_author[name]:
                self.root.addPlugin(plugin.identifier, plugin.name,
                                    plugin.summary, plugin.version)

    def callback(self, values):
        self.root.showGridPlugins()
        for i, plugin in enumerate(values):
            plugin.identifier = i + 1
            self.root.addPlugin(plugin.identifier, plugin.name,
                                plugin.summary, plugin.version)
            self._plugins[plugin.identifier] = plugin

    def show_plugin_details(self, identifier):
        plugin = self._plugins[identifier]
        self._counter = 1
        self._counter_callback = self._show_details

        if plugin.shallow:
            self.connect(plugin,
                         SIGNAL("pluginMetadataInflated(PyQt_PyObject)"),
                         self._update_content)
            self._plugins_inflate.append(plugin.inflate())
        else:
            self._update_content(plugin)

    def _load_tags_grid(self):
        self._categoryTags = True
        self._counter = len(self._plugins)
        self.root.updateCategoryCounter(self._counter)
        self._counter_callback = self._show_tags_grid
        self._inflating_plugins = list(self._plugins.values())
        self._loading_function()

    def _load_author_grid(self):
        self._categoryTags = False
        self._counter = len(self._plugins)
        self.root.updateCategoryCounter(self._counter)
        self._counter_callback = self._show_author_grid
        self._inflating_plugins = list(self._plugins.values())
        self._loading_function()

    def _load_search_results(self, search):
        self._search = search.lower().split()
        self._counter = len(self._plugins)
        self.root.updateCategoryCounter(self._counter)
        self._counter_callback = self._show_search_grid
        self._inflating_plugins = list(self._plugins.values())
        self._loading_function()

    def _loading_function(self):
        plugin = self._inflating_plugins.pop()
        if plugin.shallow:
            self.connect(plugin,
                         SIGNAL("pluginMetadataInflated(PyQt_PyObject)"),
                         self._update_content)
            self._plugins_inflate.append(plugin.inflate())
        else:
            self._process_complete(plugin)

    def _process_complete(self, plugin=None):
        self._counter -= 1
        self.root.updateCategoryCounter(self._counter)
        if self._counter == 0:
            self._counter_callback(plugin)
        else:
            self._loading_function()

    def _show_search_grid(self, plugin=None):
        self.root.showGridPlugins()
        for plugin in list(self._plugins.values()):
            keywords = plugin.keywords.lower().split() + [plugin.name.lower()]
            for word in self._search:
                if word in keywords:
                    self.root.addPlugin(plugin.identifier, plugin.name,
                                        plugin.summary, plugin.version)

    def _show_details(self, plugin):
        self.root.displayDetails(plugin.identifier)

    def _show_tags_grid(self, plugin=None):
        tags = sorted(self._plugins_by_tag.keys())
        for tag in tags:
            color = self._get_random_color(self._base_color)
            self.root.addCategory(color.name(), tag)
        self.root.loadingComplete()

    def _show_author_grid(self, plugin=None):
        authors = sorted(self._plugins_by_author.keys())
        for author in authors:
            color = self._get_random_color(self._base_color)
            self.root.addCategory(color.name(), author)
        self.root.loadingComplete()

    def _update_content(self, plugin):
        self.root.updatePlugin(
            plugin.identifier, plugin.author, plugin.author_email,
            plugin.description, plugin.download_url, plugin.home_page,
            plugin.license)
        keywords = plugin.keywords.split()
        for key in keywords:
            plugins = self._plugins_by_tag[key]
            if plugin not in plugins:
                plugins.append(plugin)
                self._plugins_by_tag[key] = plugins
        plugins = self._plugins_by_author[plugin.author]
        if plugin not in plugins:
            plugins.append(plugin)
            self._plugins_by_author[plugin.author] = plugins
        self.emit(SIGNAL("processCompleted(PyQt_PyObject)"), plugin)

    def _get_random_color(self, mix=None):
        red = random.randint(0, 256)
        green = random.randint(0, 256)
        blue = random.randint(0, 256)

        # mix the color
        if mix:
            red = (red + mix.red()) / 2
            green = (green + mix.green()) / 2
            blue = (blue + mix.blue()) / 2

        color = QColor(red, green, blue)
        return color