Beispiel #1
0
def main():
    app = QApplication(sys.argv)

    window = MainWindow()
    window.show()

    app.exec_()
def main():
    app = QApplication([])
    QtWebEngine.initialize()
    engine = QQmlApplicationEngine()
    qml_file_path = os.path.join(os.path.dirname(__file__), 'browser.qml')
    qml_url = QUrl.fromLocalFile(os.path.abspath(qml_file_path))
    engine.load(qml_url)
    app.exec_()
Beispiel #3
0
    def testIt(self):
        app = QApplication([])
        self.box = MySpinBox()
        self.box.show()

        QTimer.singleShot(0, self.sendKbdEvent)
        QTimer.singleShot(100, app.quit)
        app.exec_()

        self.assertEqual(self.box.text(), '0')
Beispiel #4
0
def main():
    global dbus
    parser = ArgumentParser()
    parser.add_argument("-v", "--verbose", help="increase output verbosity",
                        action="store_true")
    args = parser.parse_args()
    QtQml.qmlRegisterType(QmlPage, "djpdf", 1, 0, "DjpdfPage")
    app = QApplication([])
    engine = QQmlApplicationEngine()
    thumbnail_image_provider = ThumbnailImageProvider()
    engine.addImageProvider("thumbnails", thumbnail_image_provider)
    ctx = engine.rootContext()
    pages_model = QmlPagesModel(verbose=args.verbose)
    if os.environ.get("DJPDF_PLATFORM_INTEGRATION", "") == "flatpak":
        import dbus
        import dbus.mainloop.glib
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        bus = dbus.SessionBus()
        platform_integration = QmlFlatpakPlatformIntegration(bus)
    else:
        platform_integration = QmlPlatformIntegration()
    ctx.setContextProperty("pagesModel", pages_model)
    ctx.setContextProperty("platformIntegration", platform_integration)
    engine.load(QUrl.fromLocalFile(
        os.path.join(QML_DIR, "main.qml")))
    if os.environ.get("DJPDF_PLATFORM_INTEGRATION", "") == "flatpak":
        platform_integration.win_id = engine.rootObjects()[0].winId()
    exit(app.exec_())
def run_main():
    import sys
    from PySide2.QtWidgets import QApplication
    app = QApplication(sys.argv)
    mw = AddressWidget()
    mw.show()
    sys.exit(app.exec_())
Beispiel #6
0
def main():
    # load options from cmdline
    parser = create_parser()
    args = parser.parse_args()

    # set debug levels
    LEVELS = {
        'notset': logging.NOTSET,
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL,
    }

    level_name = 'info'
    if args.debug:
        level_name = args.debug
    level = LEVELS.get(level_name, logging.INFO)

    # now get the logger used in the common module and set its level to what
    # we get from sys.argv
    commonlogger.setLevel(level)
    logger.setLevel(level)

    formatter = logging.Formatter('[%(levelname)s] %(name)s %(message)s')

    handler = logging.StreamHandler(stream=sys.stdout)
    handler.setFormatter(formatter)
    handler.setLevel(logging.DEBUG)

    logger.addHandler(handler)
    commonlogger.addHandler(handler)

    app = QApplication(sys.argv)

    frame = MainWindow()
    # args is defined at the top of this module
    if not args.hidden:
        # Need to fix showing wrong window
        frame.show()

    sys.exit(app.exec_())
Beispiel #7
0
def main():
    app = QApplication(sys.argv)

    root = coin.SoSeparator()
    

    vert = coin.SoVertexShader()
    vert.sourceProgram = "vertex.glsl"
    
    frag = coin.SoFragmentShader()
    frag.sourceProgram = "frag.glsl"
    
    shaders = [vert,frag]
    pro = coin.SoShaderProgram()
    pro.shaderObject.setValues(0,len(shaders),shaders)
    
    
    mat = coin.SoMaterial()
    mat.diffuseColor.setValue(coin.SbColor(0.8, 0.8, 0.8))
    mat.specularColor.setValue(coin.SbColor(1, 1, 1))
    mat.shininess.setValue(1.0)
    mat.transparency.setValue(0.5)
    
    
    
    
    sphere = coin.SoSphere()
    sphere.radius = 1.2
    
    
    root.addChild(pro)
    root.addChild(sphere)
    root.addChild(mat)
    root.addChild(coin.SoCube())

    viewer = quarter.QuarterWidget()
    viewer.setSceneGraph(root)

    viewer.setWindowTitle("minimal")
    viewer.show()
    sys.exit(app.exec_())
Beispiel #8
0
class TilePad(object):

    Instance = None

    @staticmethod
    def Run():
        TilePad.Instance = TilePad()
        return TilePad.Instance.run()

    def __init__(self):
        QCoreApplication.setOrganizationName('DynArt')
        QCoreApplication.setApplicationName('TilePad')
        QCoreApplication.setApplicationVersion('0.4.0')
        if getattr(sys, 'frozen', False):
            self.dir = os.path.dirname(sys.executable)
        else:
            self.dir = os.path.dirname(__file__)
        self.dir = self.dir.replace('\\', '/')
        self.qApp = QApplication(sys.argv)
        self.mainWindow = MainWindow(self)

    def run(self):
        self.mainWindow.show()
        return self.qApp.exec_()
Beispiel #9
0
def main():

    logic = Logic()

    # Serial to Arduino
    # serial_reader = SerialReader()
    serial_reader = SerialReader()
    while not serial_reader.isOpen:
        serial_reader.try_open()

    # TCP Server to rPi
    tcp_server = TCP_Server()
    tcp_server.catch_client()

    QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
    app = QApplication([])
    window = TseMainWindow()

    # logika
    serial_reader.signals.message.connect(window.parse_incoming_message)
    serial_reader.signals.message.connect(logic.update)

    # przyciski HOME
    window.ui.btn_homing.clicked.connect(window.prepare_message_homing)
    window.ui.btn_homing_ack.clicked.connect(
        lambda x: serial_reader.write("9"))
    window.signals.sendSerial.connect(serial_reader.write)

    # from GUI dx dy to cal logic
    window.signals.sliderPosOrient.connect(logic.slider_pos_orient)
    # from logic to update sliders with wanted pos
    logic.signals.setUserSliderValues.connect(window.update_user_sliders)

    # apexes from logic to gui update
    logic.signals.setCurrentPosOrient.connect(window.update_current_posorient)
    logic.signals.setWantedPosOrient.connect(window.update_wanted_posorient)

    # task sending
    window.ui.btn_task.clicked.connect(window.prepare_message_task)

    # tcp camera message -> gui update
    tcp_server.signals.message_camera.connect(window.update_camera_target_info)
    # tcp imu message -> gui update
    tcp_server.signals.message_imu.connect(window.update_imu_label)

    # logic to dx dy ... predictions
    tcp_server.signals.message_camera.connect(
        logic.get_dposorient_to_follow_target)
    logic.signals.setFollowedUserSliders.connect(
        window.update_target_follow_derivatives)

    # timers interruptions, send task to TSE when enable
    window.send_task_timer.timeout.connect(window.prepare_message_task)

    # handle test pos button and set slider to zero button
    window.ui.btn_autosend.clicked.connect(window.send_task_timer_callback)

    window.ui.btn_test_pos.clicked.connect(window.set_sliders_to_test)
    window.ui.btn_zero.clicked.connect(window.set_d_sliders_to_zero)

    # loop button callback
    window.ui.btn_loop.clicked.connect(window.loop_button_callback)
    # log to file button callback
    window.ui.btn_log_to_file.clicked.connect(window.log_to_file_callback)

    # stabilize button enabled
    # window.ui.btn_stabilize.clicked.connect(window.stabilize_callback)

    #threading Serial and TCP
    thread = threading.Thread(target=serial_reader.loop, daemon=True)
    thread.start()

    thread2 = threading.Thread(target=tcp_server.loop, daemon=True)
    thread2.start()

    app.aboutToQuit.connect(lambda: serial_reader.stop())
    app.aboutToQuit.connect(lambda: tcp_server.stop())
    app.exec_()
def test():
    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    win = ApplicationWindow()
    win.showMaximized()
    sys.exit(app.exec_())

class MyMainWindow(QFrame):
    def __init__(self, parent=None):
        QFrame.__init__(self, parent)
        palette = QPalette()
        pixmap = QPixmap("sec_shield.png")
        brush = QBrush(pixmap)
        frame_layout = QVBoxLayout()

        self.setFixedSize(300, 300)
        self.setFrameStyle(QFrame.Box)
        self.setWindowTitle("QFrame Set Background Image Example")

        #set QFrame Border Width 4 pixels
        self.setLineWidth(4)
        self.setLayout(frame_layout)

        btn1 = QPushButton(self)
        btn1.setText("Button 1")
        frame_layout.addWidget(btn1)
        palette.setBrush(QPalette.Background, brush)
        self.setPalette(palette)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MyMainWindow()
    w.show()
    app.exec_()
Beispiel #12
0
        self.pixmap = QPixmap.fromImage(image)
        self.pixmapOffset = QPoint()
        self.lastDragPosition = QPoint()
        self.pixmapScale = scaleFactor
        self.update()

    def zoom(self, zoomFactor):
        self.curScale *= zoomFactor
        self.update()
        self.thread.render(self.centerX, self.centerY, self.curScale,
                self.size())

    def scroll(self, deltaX, deltaY):
        self.centerX += deltaX * self.curScale
        self.centerY += deltaY * self.curScale
        self.update()
        self.thread.render(self.centerX, self.centerY, self.curScale,
                self.size())


if __name__ == '__main__':

    import sys

    app = QApplication(sys.argv)
    widget = MandelbrotWidget()
    widget.show()
    r = app.exec_()
    widget.thread.stop()
    sys.exit(r)
Beispiel #13
0
    customPlot.xAxis.setTickLabelFont(QFont(QFont().family(), 8))
    customPlot.yAxis.setTickLabelFont(QFont(QFont().family(), 8))

    # set axis labels:
    customPlot.xAxis.setLabel("Date")
    customPlot.yAxis.setLabel("Random wobbly lines value")

    # make top and right axes visible but without ticks and labels:
    customPlot.xAxis2.setVisible(True)
    customPlot.yAxis2.setVisible(True)
    customPlot.xAxis2.setTicks(False)
    customPlot.yAxis2.setTicks(False)
    customPlot.xAxis2.setTickLabels(False)
    customPlot.yAxis2.setTickLabels(False)

    # set axis ranges to show all data:
    customPlot.xAxis.setRange(now, now + 24 * 3600 * 249)
    customPlot.yAxis.setRange(0, 60)
    # show legend with slightly transparent background brush:
    customPlot.legend.setVisible(True)
    customPlot.legend.setBrush(QColor(255, 255, 255, 150))

    customPlot.rescaleAxes()
    customPlot.show()

    # Create and show the form
    # Run the main Qt loop
    res = app.exec_()
    customPlot = None
    sys.exit(res)
Beispiel #14
0
class QtFrontend(ViewSBFrontend):
    """ Qt Frontend that consumes packets for display. """

    UI_NAME = 'qt'
    UI_DESCRIPTION = 'proof-of-concept, unstable GUI in Qt'


    @staticmethod
    def reason_to_be_disabled():
        # If we weren't able to import pyside2, disable the library.
        if 'QWidget' not in globals():
            return "pyside2 (qt library) not available"

        return None


    def __init__(self):
        """ Sets up the Qt UI. """

        QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)

        self.app = QApplication([])
        self.ui_file = QtCore.QFile(os.path.dirname(os.path.realpath(__file__)) + '/qt.ui')

        self.loader = QUiLoader()
        self.window: QtWidgets.QMainWindow = self.loader.load(self.ui_file)

        # The default column size of 100 is too small for the summary column.
        self.window.usb_tree_widget.setColumnWidth(1, 400)

        self.window.update_timer = QtCore.QTimer()
        self.window.update_timer.timeout.connect(self.update)

        self.window.usb_tree_widget.currentItemChanged.connect(self.tree_current_item_changed)

        self.window.usb_tree_widget: QtWidgets.QTreeWidget = self.window.usb_tree_widget
        self.window.usb_tree_widget.sortByColumn(0)


        self.window.showMaximized()


    def update(self):
        """ Called by the QTimer `update_timer`, collects packets waiting the queue and adds them to the tree view.

        Note: Since this is called via a QTimer signal, this method runs in the UI thread.
        """

        packet_list = []

        try:
            # Get as many packets as we can as quick as we can.
            while(True):

                packet = self.data_queue.get_nowait()
                packet_list.append(packet)

        # But the instant it's empty, don't wait for any more; just send them to be processed.
        except multiprocessing.queues.Empty:
            pass

        finally:
            # In case the queue was empty in the first place and didn't have anything ready.
            if len(packet_list) > 0:

                self.add_packets(packet_list)


    def add_packets(self, viewsb_packets: []):
        """ Adds a list of top-level ViewSB packets to the tree.

        We're in the UI thread; every bit of overhead counts, so let's batch as much as possible.
        """

        for viewsb_packet in viewsb_packets:
            top_level_item = QtWidgets.QTreeWidgetItem(get_packet_string_array(viewsb_packet))
            top_level_item.setData(0, QtCore.Qt.UserRole, viewsb_packet)

            list_of_children = []
            recursive_packet_walk(viewsb_packet, list_of_children)

            top_level_item.addChildren(list_of_children)

            self.window.usb_tree_widget.addTopLevelItem(top_level_item)

    def tree_current_item_changed(self, current_item, previous_item):
        """ Use the side panel to show a detailed view of the current item. """

        # Clear the details widget.
        self.window.usb_details_tree_widget.clear()

        self.window.usb_details_tree_widget.setColumnCount(2)

        current_packet: ViewSBPacket = current_item.data(0, QtCore.Qt.UserRole)

        # A list of 2-tuples: first element is a table title, and the second is usually a string: string dict
        detail_fields = current_packet.get_detail_fields()

        # Each table will have a root item in the details view.
        root_items = []

        for table in detail_fields:
            title: str = table[0]

            root = QtWidgets.QTreeWidgetItem([title])
            children = []

            fields = table[1]

            # The usual case: a str: str dict.
            if type(fields) == type({}):
                for key, value in fields.items():
                    children.append(QtWidgets.QTreeWidgetItem(stringify_list([key, value])))

            # Sometimes a descriptor will just be a 1-column list.
            elif type(fields) == type([]):
                for item in fields:
                    children.append(QtWidgets.QTreeWidgetItem([str(item)]))

            # Sometimes it'll just be a string, or, if it's an unknown descriptor, a `bytes` instance.
            else:
                children.append(QtWidgets.QTreeWidgetItem([str(fields)]))

            root.addChildren(children)

            # Add an empty "item" between each table
            root_items += [root, QtWidgets.QTreeWidgetItem([])]


        self.window.usb_details_tree_widget.addTopLevelItems(root_items)

        self.window.usb_details_tree_widget.expandAll()

        self.window.usb_details_tree_widget.resizeColumnToContents(0)
        self.window.usb_details_tree_widget.resizeColumnToContents(1)

    def run(self):
        """ Overrides `ViewSBFrontend.run()` """

        # TODO: is there a better value than 100 ms? Should it be configurable by the Analyzer?
        self.window.update_timer.start(100)
        self.app.exec_()
        self.stop()

    def stop(self):
        self.app.closeAllWindows()
        self.termination_event.set()
class Application:
    def __init__(self, argv):
        self.plumbing_bridge = PlumbingBridge()
        self.daq_bridge = DAQBridge(self.plumbing_bridge)
        self.controls_bridge = ControlsBridge(self.plumbing_bridge)
        self.procedures_bridge = ProceduresBridge(self.plumbing_bridge,
                                                  self.controls_bridge)

        self.app = QApplication(argv)

        # ALL custom built QQuickItems have to be registered as QML objects in this way:
        qmlRegisterType(QMLVisualizationArea, 'VisualizationArea', 1, 0,
                        'VisualizationArea')

        self.app.setWindowIcon(QIcon(find_resource('icon.ico')))
        self.app.setOrganizationName('Waterloo Rocketry')
        self.app.setOrganizationDomain('waterloorocketry.com')
        self.app.setApplicationName('Topside')

        self.qml_engine = QQmlEngine()
        context = self.qml_engine.rootContext()
        context.setContextProperty('plumbingBridge', self.plumbing_bridge)
        context.setContextProperty('controlsBridge', self.controls_bridge)
        context.setContextProperty('proceduresBridge', self.procedures_bridge)

        self.main_window = self._make_main_window()

        # TODO(jacob): Currently we load these example files at startup
        # to make testing turnaround a bit faster. Figure out how to
        # make the application remember the last file opened, and open
        # that instead.
        self.plumbing_bridge.load_from_files([find_resource('example.pdl')])
        self.procedures_bridge.load_from_file(find_resource('example.proc'))
        self.controls_bridge.refresh()

    def _make_main_window(self):
        # TODO(jacob): Should we move this code somewhere else (maybe
        # into a separate MainWindow class)?
        window = QMainWindow()

        vert_splitter = QSplitter(Qt.Vertical)
        vert_splitter.setChildrenCollapsible(False)

        horiz_splitter = QSplitter(Qt.Horizontal)
        horiz_splitter.setChildrenCollapsible(False)

        daq_widget = make_daq_widget(self.daq_bridge, self.plumbing_bridge)
        horiz_splitter.addWidget(daq_widget)

        plumb_widget = make_qml_widget(self.qml_engine, 'PlumbingPane.qml')
        plumb_widget.setMinimumWidth(600)
        plumb_widget.setMinimumHeight(600)
        horiz_splitter.addWidget(plumb_widget)

        proc_widget = make_qml_widget(self.qml_engine, 'ProceduresPane.qml')
        proc_widget.setMinimumWidth(400)
        proc_widget.setMinimumHeight(600)
        horiz_splitter.addWidget(proc_widget)

        vert_splitter.addWidget(horiz_splitter)

        controls_widget = make_qml_widget(self.qml_engine, 'ControlsPane.qml')
        controls_widget.setMinimumHeight(200)

        vert_splitter.addWidget(controls_widget)

        window.setCentralWidget(vert_splitter)

        file_menu = QMenu('&File')

        open_proc_action = QAction('Open Procedure Suite', window)
        open_proc_action.setShortcut(QKeySequence('Ctrl+O'))
        open_proc_action.triggered.connect(
            self.procedures_bridge.loadFromDialog)
        file_menu.addAction(open_proc_action)

        open_plumb_action = QAction('Open Plumbing Engine', window)
        open_plumb_action.setShortcut(QKeySequence('Ctrl+Shift+O'))
        open_plumb_action.triggered.connect(
            self.plumbing_bridge.loadFromDialog)
        file_menu.addAction(open_plumb_action)

        exit_action = QAction('Exit', window)
        exit_action.setShortcut(QKeySequence.Quit)
        exit_action.triggered.connect(window.close)
        file_menu.addAction(exit_action)

        window.menuBar().addMenu(file_menu)

        tools_menu = QMenu('&Tools')

        pdl_editor_action = QAction('PDL Editor', window)
        pdl_editor_action.setShortcut(QKeySequence('Ctrl+Shift+E'))
        pdl_editor_action.triggered.connect(self.launchPDLEditor)
        tools_menu.addAction(pdl_editor_action)

        window.menuBar().addMenu(tools_menu)

        return window

    @Slot()
    def launchPDLEditor(self):
        w = make_pdl_editor(self.main_window)
        w.show()

    def run(self):
        self.app.aboutToQuit.connect(self.shutdown)

        self.main_window.showMaximized()
        app_return_code = self.app.exec_()

        return app_return_code

    def shutdown(self):
        # NOTE(jacob): We explicitly `del` this to suppress a TypeError
        # that arises from the bridges getting destroyed before the QML
        # engine, causing QML references to go invalid. We attach this
        # cleanup to the aboutToQuit signal because app.exec_ is not
        # guaranteed to return, and therefore placing it immediately
        # after the app.exec_ call would not guarantee that this cleanup
        # routine runs.
        # For reference: https://bugreports.qt.io/browse/QTBUG-81247
        del self.qml_engine
Beispiel #16
0
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


if __name__ == "__main__":

    application = QApplication(sys.argv)

    db = QSqlDatabase.addDatabase("QSQLITE")
    print("set database driver")
    db.setDatabaseName("test.db")
    print("select test database")

    model = Model()
    print("create model")
    model.setTable("units")
    print("select units table")
    model.select()
    print("select table data")

    view = View()
    table = MainTable()
    table.setModel(model)
    view.setCentralWidget(table)

    view.show()
    print("show view")

    sys.exit(application.exec_())
Beispiel #17
0
    def volleyball_button_handler(self):
        kwargs = dict()

        if self.ui.home_text.text() != '':
            kwargs['home'] = self.ui.home_text.text()

        if self.ui.visitor_text.text() != '':
            kwargs['visitor'] = self.ui.visitor_text.text()

        if self.ui.server_ip.text() != '':
            kwargs['serverIP'] = self.ui.server_ip.text()

        volleyball = VolleyballGUI(**kwargs)

        self.close()

        volleyball.show()
        volleyball.exec()


if __name__ == '__main__':

    QApplication.setAttribute(Qt.ApplicationAttribute.AA_EnableHighDpiScaling,
                              True)
    APP = QApplication(sys.argv)

    WINDOW = ScoresnakeGUI()
    WINDOW.show()
    sys.exit(APP.exec_())
Beispiel #18
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
from PySide2.QtWidgets import QApplication, QWidget


class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(0, 0, 800, 600)
        # 坐标0 0 大小800 600
        self.setWindowTitle('myapp')


if __name__ == '__main__':
    myapp = QApplication(sys.argv)
    mywidget = MyWidget()
    mywidget.show()
    sys.exit(myapp.exec_())
def main():
    app = QApplication(sys.argv)
    ex = UI_Window()
    ex.show()
    sys.exit(app.exec_())
Beispiel #20
0
class Main(object):
    """主程序"""
    def __init__(self):
        self.loadIni()  # 加载配置文件
        self.app = QApplication(sys.argv)
        self.loadUi()  # 加载ui
        self.attribute()  # 属性
        self.connect()  # 槽连接
        self.window.show()
        sys.exit(self.app.exec_())

    def loadIni(self):
        """获取配置文件"""
        with open(RESOURCES_ROOT + "/setting.ini", "r") as file:
            text = file.read()
            thread_num = int(findall(r"thread_num = (\d+);", text)[0])
            Spider.thread_num = thread_num

    def attribute(self):
        """属性"""
        # 图标
        self.window.setWindowIcon(QIcon(RESOURCES_ROOT + "/magnet.ico"))
        # 磁力爬虫
        self.spider = Spider()
        self.spider_thread = None
        # 爬虫线程锁
        self.lock = Lock()
        # 右键菜单
        self.rightMenu = QMenu(self.window.search_out)
        # 剪切板
        self.clipboard = QApplication.clipboard()

    def loadUi(self):
        """加载ui文件"""
        # 主ui
        ui = QFile(UI_ROOT + "/main.ui")
        ui.open(QFile.ReadOnly)
        ui.close()
        self.window = QUiLoader().load(ui)

    def connect(self):
        """槽连接"""
        # 搜索框和按钮
        self.window.search_button.clicked.connect(self.search)
        self.window.input_box.returnPressed.connect(self.search)
        # 磁力搜索线程
        self.spider.status_change.connect(self.searchStatusChange)
        self.spider.result_add.connect(self.outputBoxAdd)
        # 右键菜单
        action = self.rightMenu.addAction("复制")
        action.triggered.connect(self.rightCopy)
        self.window.search_out.setContextMenuPolicy(Qt.CustomContextMenu)
        self.window.search_out.customContextMenuRequested.connect(
            lambda: self.rightMenu.exec_(QCursor.pos()))

    def searchStatusChange(self):
        """爬虫运行状态改变"""
        status = self.spider.getStatus()
        if status:  # 如果爬虫运行中
            self.window.search_status.setText("运行中")
            self.window.search_button.setText("停止")
        else:
            self.window.search_status.setText("未运行")
            self.window.search_button.setText("搜索")

    @Slot(Magnet)
    def outputBoxAdd(self, result: Magnet):
        """磁力增加到GUI"""
        self.lock.acquire()
        # 计数以及表格行数变更
        count = self.window.search_out.rowCount()
        result.id_num = count + 1
        self.window.search_out.setRowCount(count + 1)
        # 设置值
        self.window.search_out.setItem(count, 0,
                                       QTableWidgetItem(result.domain))
        self.window.search_out.setItem(count, 1,
                                       QTableWidgetItem(result.title))
        self.window.search_out.setItem(count, 2, QTableWidgetItem(result.size))
        self.window.search_out.setItem(count, 3,
                                       QTableWidgetItem(result.download))
        self.window.search_out.setItem(count, 4,
                                       QTableWidgetItem(result.create_time))
        self.lock.release()

    def search(self):
        """搜索"""
        bt_text = self.window.search_button.text()
        if bt_text == "搜索":
            # 删除原有的
            Magnet.all.clear()
            self.window.search_out.setRowCount(0)
            self.window.search_out.clearContents()
            # 搜索
            content = self.window.input_box.text()
            if content:
                self.spider.setContent(content)
                self.spider_thread = Thread(target=self.spider.runMagnet)
                self.spider_thread.start()
        else:  # 停止
            self.spider.stop()

    def rightCopy(self):
        """右键菜单:复制"""
        try:
            select_item = self.window.search_out.selectedItems()[0]
            row = select_item.row()
            for magnet in Magnet.all:
                if magnet.id_num == row + 1:
                    if magnet.hash:
                        self.clipboard.setText(magnet.hash)
                    elif magnet.magnet_content:
                        self.clipboard.setText(magnet.magnet_content)
                    else:
                        self.clipboard.setText(magnet.torrent)
                    break
        except:
            pass
Beispiel #21
0
def main():
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    QMessageBox.information(None, "Info", "Just drag and drop the items.")
    sys.exit(app.exec_())
Beispiel #22
0
def _test_pipedimagerpq():
    # vertices of a pentagon (roughly) centered in a 1000 x 1000 square
    pentagonpts = (
        (504.5, 100.0),
        (100.0, 393.9),
        (254.5, 869.4),
        (754.5, 869.4),
        (909.0, 393.9),
    )
    linepts = ((350, 50), (200, 150), (400, 250), (300, 350), (150, 250),
               (100, 450))
    # start PyQt
    testapp = QApplication(["PipedImagerPQ"])
    # create the list of commands to submit
    drawcmnds = []
    drawcmnds.append({"action": "setTitle", "title": "Tester"})
    drawcmnds.append({"action": "show"})
    drawcmnds.append({"action": "clear", "color": "black"})
    drawcmnds.append({"action": "screenInfo"})
    # create the image to be displayed
    testimage = QImage(500, 500, QImage.Format_ARGB32_Premultiplied)
    # initialize a black background
    testimage.fill(0xFF000000)
    # draw some things in the image
    testpainter = QPainter(testimage)
    testpainter.setBrush(QBrush(QColor(0, 255, 0, 128), Qt.SolidPattern))
    testpainter.setPen(
        QPen(QBrush(QColor(255, 0, 0, 255), Qt.SolidPattern), 5.0,
             Qt.SolidLine, Qt.SquareCap, Qt.MiterJoin))
    testpainter.drawRect(QRectF(5.0, 255.0, 240.0, 240.0))
    testpainter.setBrush(QBrush(QColor(0, 0, 255, 255), Qt.SolidPattern))
    testpainter.setPen(
        QPen(QBrush(QColor(0, 0, 0, 255), Qt.SolidPattern), 5.0, Qt.DashLine,
             Qt.RoundCap, Qt.RoundJoin))
    testpainter.drawPolygon(
        QPolygonF([
            QPointF(.25 * ptx, .25 * pty + 250) for (ptx, pty) in pentagonpts
        ]))
    testpainter.setBrush(Qt.NoBrush)
    testpainter.setPen(
        QPen(QBrush(QColor(255, 255, 255, 255), Qt.SolidPattern), 3.0,
             Qt.DashLine, Qt.RoundCap, Qt.RoundJoin))
    testpainter.drawPolyline(
        QPolygonF([QPointF(pts, pty) for (pts, pty) in linepts]))
    testpainter.end()
    # add the image command
    testimgwidth = testimage.width()
    testimgheight = testimage.height()
    testimgstride = testimage.bytesPerLine()
    # not a good way to get the pixel data
    testimgdata = bytearray(testimgheight * testimgstride)
    k = 0
    for pty in range(testimgheight):
        for ptx in range(testimgwidth):
            pixval = testimage.pixel(ptx, pty)
            (aval, rgbval) = divmod(pixval, 256 * 256 * 256)
            (rval, gbval) = divmod(rgbval, 256 * 256)
            (gval, bval) = divmod(gbval, 256)
            testimgdata[k] = bval
            k += 1
            testimgdata[k] = gval
            k += 1
            testimgdata[k] = rval
            k += 1
            testimgdata[k] = aval
            k += 1
    testblocksize = 4000
    testnumblocks = (testimgheight * testimgstride + testblocksize -
                     1) // testblocksize
    drawcmnds.append({
        "action": "newImage",
        "width": testimgwidth,
        "height": testimgheight,
        "stride": testimgstride
    })
    for k in range(testnumblocks):
        if k < (testnumblocks - 1):
            blkdata = testimgdata[k * testblocksize:(k + 1) * testblocksize]
        else:
            blkdata = testimgdata[k * testblocksize:]
        drawcmnds.append({
            "action": "newImage",
            "blocknum": k + 1,
            "numblocks": testnumblocks,
            "startindex": k * testblocksize,
            "blockdata": blkdata
        })
    # finish the command list
    drawcmnds.append({"action": "show"})
    drawcmnds.append({"action": "exit"})
    # create a PipedImagerPQ in this process
    (cmndrecvpipe, cmndsendpipe) = multiprocessing.Pipe(False)
    (rspdrecvpipe, rspdsendpipe) = multiprocessing.Pipe(False)
    testviewer = PipedImagerPQ(cmndrecvpipe, rspdsendpipe)
    # create a command submitter dialog
    tester = _CommandSubmitterPQ(testviewer, cmndsendpipe, rspdrecvpipe,
                                 drawcmnds)
    tester.show()
    # let it all run
    testresult = testapp.exec_()
    if testresult != 0:
        sys.exit(testresult)
Beispiel #23
0
def run_application():
    """Start application."""
    qt_app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(qt_app.exec_())
Beispiel #24
0
if __name__ == '__main__':
    app = QApplication([])  # 初始化应用

    #
    # 检查是否需要验证产品密钥
    #
    login_dial = LoginDialog()
    if login_dial.check() or login_dial.exec_():
        #
        # 显示界面
        #
        main_window = MainWindow()  # 创建主窗口
        # main_window.ui.show()  # 按实际大小显示窗口
        main_window.ui.showMaximized()  # 全屏显示窗口,必须要用,不然不显示界面

        #
        # 子线程启动
        #
        serial_worker = SerialWorker(main_window)
        serial_worker.start()
        check_worker = CheckWorker(main_window)
        check_worker.start()

        #
        # 关闭界面了,强制关闭子线程
        #
        if app.exec_() == 0:
            serial_worker.terminate()
            check_worker.terminate()
Beispiel #25
0
def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
Beispiel #26
0
        self.view.scene.camera = camera
        #self.repaint()
        self.view.start_rendering()
        self.view.update()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Provide a chemical input file")
    parser.add_argument(
        "-i",
        "--input",
        type=str,
        help="an input file, accepted types: mol2, pdb, xyz, gsd")
    parser.add_argument(
        "-t",
        "--frame",
        type=int,
        default="-1",
        help=
        "if trajectory file is given, which frame to diffract (default -1 or last frame)"
    )
    args = parser.parse_args()

    qapp = QApplication([])

    app = ApplicationWindow(args.input, args.frame)
    app.show()

    qapp.exec_()
Beispiel #27
0
def main():
    """main function
    """
    # Adds Ctrl+C support to kill app
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)

    app = QApplication(sys.argv)
    app.setOrganizationName("djieffx")
    app.setApplicationName("vspleeter")
    loader = QUiLoader()
    mw = loader.load(
        os.path.join(os.path.dirname(__file__), "vspleeter_mainWindow.ui"))
    mw.setWindowIcon(QIcon(":/icons/vspleeter_icon.png"))

    def getBinaries():
        """Create a generator that yield the proper command name if the checkbox is checked.

        :return: generator with command name
        :rtype: generator
        """
        if mw.cpuCheckBox.checkState():
            yield 'spleeter'
        if mw.gpuCheckBox.checkState():
            yield 'spleeter-gpu'

    def getStemsAmount():
        """Create a generator that yield the stems amount if the checkbox is checked.

        :return: generator with stem count
        :rtype: generator
        """
        if mw.stems2CheckBox.checkState():
            yield '2'
        if mw.stems4CheckBox.checkState():
            yield '4'
        if mw.stems5CheckBox.checkState():
            yield '5'

    def createOutputDir(cmdSpecs):
        """Create the output directory from defined output specifications

        :param cmdSpecs: context based variables to execute spleeter command
        :type cmdSpecs: dict

        :return: the output directory
        :rtype: str
        """
        outputDir = OUTPUT_PATH_SUFFIX.format(**cmdSpecs)
        if not os.path.exists(outputDir):
            os.makedirs(outputDir, mode=0o777)
            print('Created the {0} directory'.format(outputDir))

        return outputDir

    def generateCommandsPerElements(binaryGenerator, inputFilePath,
                                    stemsCPUGenerator, stemsGPUGenerator,
                                    rootOutputDir):
        """Generate all the commands necessary, per what is selected in the UI, looping on the process type

        :param binaryGenerator: generator with all the binary selections
        :param str inputFilePath: The file to be spleeted
        :param stemsCPUGenerator: generator with the CPU processes flag
        :param stemsGPUGenerator: generator with the GPU processes flag
        :param str rootOutputDir: The output directory

        :return: generator with all command line to spleet the file
        """
        for binaryName in binaryGenerator:
            cmdSpecs = {
                'rootOutputDir': rootOutputDir,
                'basename':
                os.path.basename(os.path.splitext(inputFilePath)[0]),
                'binaryType': 'CPU',
                'binaryName': binaryName,
                'inputFilePath': inputFilePath,
                'stemsGenerator': stemsCPUGenerator
            }
            if 'gpu' in binaryName:
                cmdSpecs['binaryType'] = 'GPU'
                cmdSpecs['stemsGenerator'] = stemsGPUGenerator
                yield from generateCmdPerStem(cmdSpecs)
            else:
                yield from generateCmdPerStem(cmdSpecs)

    def generateCmdPerStem(cmdSpecs):
        """Generate the command from the stem count

        :param dict cmdSpecs: a dictionary containing all necessary data to generate the command

        :return: a command to execute
        :rtype: list
        """
        stemsGenerator = cmdSpecs['stemsGenerator']
        for stemNum in stemsGenerator:
            cmdSpecs['stemNum'] = stemNum
            outputDir = createOutputDir(cmdSpecs)
            if os.name == 'nt':
                cmd = [
                    "python", "-m", "{}".format(cmdSpecs['binaryName']),
                    "separate", "-i", "{}".format(cmdSpecs['inputFilePath']),
                    "-p", "spleeter:{}stems".format(cmdSpecs['stemNum']), "-o",
                    "{}".format(outputDir)
                ]
            else:
                cmd = [
                    "{}".format(cmdSpecs['binaryName']), "separate", "-i",
                    "{}".format(cmdSpecs['inputFilePath']), "-p",
                    "spleeter:{}stems".format(cmdSpecs['stemNum']), "-o",
                    "{}".format(outputDir)
                ]
            yield cmd

    def browseForInputFile(_):
        """Opens a file browser, and set the input file

        :param _: unused
        """
        inputFile = QFileDialog.getOpenFileName()[0]
        mw.inputFileLineEdit.setText(inputFile)
        checkToEnableProcess()

    def browseForOutputDir(_):
        """Opens a file browser, and set the input file

        :param _: unused
        """
        outputDir = QFileDialog.getExistingDirectory()
        mw.outputDirLineEdit.setText(outputDir)
        checkToEnableProcess()

    def checkToEnableProcess():
        """If all the necessary params are set, enable the process button"""
        mw.processPushButton.setEnabled(False)

        inputFileCheck = bool(mw.inputFileLineEdit.text())
        procCheck = any([
            mw.cpuCheckBox.checkState(),
            mw.gpuCheckBox.checkState(),
        ])
        stemsCheck = any([
            mw.stems2CheckBox.checkState(),
            mw.stems4CheckBox.checkState(),
            mw.stems5CheckBox.checkState(),
        ])
        outputFileCheck = bool(mw.outputDirLineEdit.text())

        if all([
                inputFileCheck,
                procCheck,
                stemsCheck,
                outputFileCheck,
        ]):
            mw.processPushButton.setEnabled(True)

    def processBatchElements(_):
        """Process all the data from the UI, and execute all the commands generated

        :param _: unused input
        """
        binaryGenerator = getBinaries()
        inputFilePath = mw.inputFileLineEdit.text()
        stemsCPUGenerator = getStemsAmount()
        stemsCPUGenerator, stemsGPUGenerator = itertools.tee(stemsCPUGenerator)
        rootOutputDir = mw.outputDirLineEdit.text()

        generatedCmds = generateCommandsPerElements(binaryGenerator,
                                                    inputFilePath,
                                                    stemsCPUGenerator,
                                                    stemsGPUGenerator,
                                                    rootOutputDir)

        generatedCmds, generatedCmdsForLength = itertools.tee(generatedCmds)

        amountOfCommands = 0
        for _ in generatedCmdsForLength:
            amountOfCommands += 1

        mw.progressBar.setRange(0, amountOfCommands)
        mw.progressBar.setValue(0)
        mw.resultTextEdit.setText('')
        mw.resultTextEdit.append('Source File: %s' % inputFilePath)

        for cmd in generatedCmds:
            currentJobCount = mw.progressBar.value()
            subprocess.run(cmd)

            mw.progressBar.setValue(currentJobCount + 1)

            mw.resultTextEdit.append('Output %s:' % cmd[5].split(':')[1])
            outputFiles = glob.glob(os.path.join(cmd[7], '*', '*'))
            for outputFile in outputFiles:
                mw.resultTextEdit.append(outputFile)
            mw.resultTextEdit.append('')

    checkToEnableProcess()

    mw.inputFilePushButton.clicked.connect(browseForInputFile)
    mw.outputDirPushButton.clicked.connect(browseForOutputDir)

    mw.cpuCheckBox.stateChanged.connect(checkToEnableProcess)
    mw.gpuCheckBox.stateChanged.connect(checkToEnableProcess)

    mw.stems2CheckBox.stateChanged.connect(checkToEnableProcess)
    mw.stems4CheckBox.stateChanged.connect(checkToEnableProcess)
    mw.stems5CheckBox.stateChanged.connect(checkToEnableProcess)

    mw.processPushButton.clicked.connect(processBatchElements)
    mw.actionexit.triggered.connect(app.quit)
    mw.show()
    sys.exit(app.exec_())
Beispiel #28
0
    def createSlider(self):
        hbox = QHBoxLayout()

        self.slider = QSlider()
        self.slider.setOrientation(Qt.Horizontal)
        self.slider.setTickPosition(QSlider.TicksBelow)
        self.slider.setTickInterval(10)
        self.slider.setMinimum(0)
        self.slider.setMaximum(100)

        self.slider.valueChanged.connect(self.changeValue)

        self.label = QLabel("0")
        self.setFont(QtGui.QFont("Sanserif", 15))

        hbox.addWidget(self.slider)
        hbox.addWidget(self.label)
        self.setLayout(hbox)

    def changeValue(self):
        size = self.slider.value()
        self.label.setText(str(size))


myApp = QApplication(sys.argv)
window = Window()
window.show()

myApp.exec_()
sys.exit(0)
Beispiel #29
0
        self.setIcon()
        self.setButton()

    def setIcon(self):
        appIcon = QIcon("icon.png")
        self.setWindowIcon(appIcon)

    def setButton(self):
        btn1 = QPushButton("Quit", self)
        btn1.move(50, 100)
        btn1.clicked.connect(self.quiteApp)

    def quiteApp(self):
        userInfo = QMessageBox.question(self, "Confirmation",
                                        "Do You Want To Quit The Application",
                                        QMessageBox.Yes | QMessageBox.No)

        if userInfo == QMessageBox.Yes:
            myapp.quit()

        elif userInfo == QMessageBox.No:
            print('Quit cancelled')


if __name__ == "__main__":
    myapp = QApplication(sys.argv)
    window = Window()
    window.show()
    myapp.exec_()
    sys.exit()
Beispiel #30
0
        self.mainUI.logBoxActionCopy.triggered.connect(
            self.mainUI.logText.copy)
        self.mainUI.logBoxActionClear.triggered.connect(
            self.mainUI.logText.clear)
        self.mainUI.logBoxActionDebug.triggered.connect(self._onClickDebug)
        self.mainUI.logBoxMenu.popup(QCursor.pos())

    def _onClickDebug(self):
        self.isDebug = bool(1 - self.isDebug)

    def onSettings(self):
        self.subUI.show()

    def onAbout(self):
        webbrowser.open('https://github.com/Matrixchung/EDAutopilot', new=1)

    def onExit(self):  # release resources
        if self.thread_script is not None: self.thread_script.terminate()
        self.thread_io.terminate()
        self.thread_image.terminate()
        self.logger.info("Resource cleared, program will exit.")
        self.thread_log.terminate()
        QApplication.instance().quit()


if __name__ == '__main__':
    app = QApplication([])
    main = Main()
    main.mainUI.show()
    sys.exit(app.exec_())
Beispiel #31
0
            self.setXRotation(self.xRot + 8 * dy)
            self.setYRotation(self.yRot + 8 * dx)
        elif event.buttons() & Qt.RightButton:
            self.setXRotation(self.xRot + 8 * dy)
            self.setZRotation(self.zRot + 8 * dx)

        self.lastPos = QPoint(event.pos())

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

    fmt = QSurfaceFormat()
    fmt.setDepthBufferSize(24)
    if "--multisample" in QCoreApplication.arguments():
        fmt.setSamples(4)
    if "--coreprofile" in QCoreApplication.arguments():
        fmt.setVersion(3, 2)
        fmt.setProfile(QSurfaceFormat.CoreProfile)
    QSurfaceFormat.setDefaultFormat(fmt)

    mainWindow = Window()
    if "--transparent" in QCoreApplication.arguments():
        mainWindow.setAttribute(Qt.WA_TranslucentBackground)
        mainWindow.setAttribute(Qt.WA_NoSystemBackground, False)

    mainWindow.resize(mainWindow.sizeHint())
    mainWindow.show()

    res = app.exec_()
    sys.exit(res)
Beispiel #32
0
    def syncMenu(self):
        self.actionPort_Config_Panel.setChecked(not self.dockWidget_PortConfig.isHidden())
        self.actionQuick_Send_Panel.setChecked(not self.dockWidget_QuickSend.isHidden())
        self.actionSend_Hex_Panel.setChecked(not self.dockWidget_SendHex.isHidden())

    def onViewChanged(self):
        checked = self._viewGroup.checkedAction()
        if checked is None:
            self.actionHEX_UPPERCASE.setChecked(True)
            self.receiver_thread.setViewMode(VIEWMODE_HEX_UPPERCASE)
        else:
            if 'Ascii' in checked.text():
                self.receiver_thread.setViewMode(VIEWMODE_ASCII)
            elif 'lowercase' in checked.text():
                self.receiver_thread.setViewMode(VIEWMODE_HEX_LOWERCASE)
            elif 'UPPERCASE' in checked.text():
                self.receiver_thread.setViewMode(VIEWMODE_HEX_UPPERCASE)

def is_hex(s):
    try:
        int(s, 16)
        return True
    except ValueError:
        return False

if __name__ == '__main__':
    app = QApplication(sys.argv)
    frame = MainWindow()
    frame.show()
    app.exec_()
Beispiel #33
0
def main():
    logging.info('main')

    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)

    appctxt = AppContext(app)

    sentry_sdk.init(
        "https://[email protected]/5210435",
        shutdown_timeout=5,
        default_integrations=False,
        # Either pyqt or pyinstaller do weird things with sentry,
        # need to explicitely specify these else sentry fails
        integrations=[
            LoggingIntegration(),
            StdlibIntegration(),
            ExcepthookIntegration(),
            DedupeIntegration(),
            AtexitIntegration(),
            ModulesIntegration(),
            ArgvIntegration(),
            ThreadingIntegration(),
        ])

    instance = SingleInstance()
    print('instance', instance)

    logger = get_logging(appctxt.build_settings['debug'])
    build_msg = "Production" if appctxt.is_frozen else "Development"
    logger.info(
        f"PWUploader, version: {appctxt.build_settings['version']}, {build_msg} build"
    )
    logging.debug(f'config {CONFIG.as_dict()}')

    signal.signal(signal.SIGINT, signal.SIG_DFL)

    logo_path = appctxt.get_resource('logo.png')
    logging.debug(f'logo_path: {logo_path}')
    icon = QIcon(logo_path)
    tray = QSystemTrayIcon()
    tray.setIcon(icon)
    logging.debug('tray: %s', tray)
    tray.show()

    menu = QMenu()

    # left-click should just open the menu too
    def on_systray_activated(reason):
        if reason == 3:
            menu.popup(QCursor.pos())

    tray.activated.connect(on_systray_activated)

    action0 = QAction(f"Version: v{appctxt.build_settings['version']}")
    menu.addAction(action0)

    action2 = QAction('settings')
    action2.triggered.connect(on_settings(appctxt))
    menu.addAction(action2)

    action3 = QAction('resync files')

    def connect_missing_files():
        upload_missing_files(appctxt, remote_config)

    action3.triggered.connect(connect_missing_files)
    menu.addAction(action3)

    action4 = QAction('open log dir')
    action4.triggered.connect(on_open_logdir)
    menu.addAction(action4)

    def toggle_always_running(state):
        if state:
            CONFIG.set('always_running', True)
            start_guardian_detached()
        else:
            CONFIG.set('always_running', False)
            kill_guardian()
        with open(CONFIG_FILE, 'w') as f:
            f.write(json.dumps(CONFIG.as_dict(), indent=2))
        logging.info('config saved')

    action5 = QAction('always running', checkable=True)
    if CONFIG.get('always_running'):
        action5.setChecked(True)
    action5.triggered.connect(toggle_always_running)
    menu.addAction(action5)

    action1 = QAction("quit")
    action1.triggered.connect(on_quit)
    menu.addAction(action1)

    tray.setContextMenu(menu)

    # FIXME get this after app display if possible
    for i in range(10):
        api = PWAPI(appctxt, appctxt.build_settings['api_url'],
                    CONFIG.get('api_token'), CONFIG.get('account_id'))
        remote_config = api.get_config()

        if 'detail' in remote_config:
            logging.error('Invalid remote config %s', remote_config)
            message = 'Unable to reach Pathology Watch API for authentication, are your API Token & Lab ID correct? Click ok to open settings.'
            response = QtWidgets.QMessageBox.question(
                None, 'API Error', message, QtWidgets.QMessageBox.Ok,
                QtWidgets.QMessageBox.Cancel)
            if response == QtWidgets.QMessageBox.Cancel:
                sys.exit(0)
            settings_dialog = SettingsDialog(appctxt, CONFIG, CONFIG_FILE)
            settings_dialog.ui.setWindowModality(QtCore.Qt.ApplicationModal)
            settings_dialog.ui.exec_()
        else:
            break
        time.sleep(1)

    if remote_config is not None:
        clean_remote_config = {
            k: v
            for k, v in remote_config.items() if 'secret' not in k
        }
        logging.debug(f'remote_config {clean_remote_config}')
        # TODO verify remote_config if it's not set, check api token or pw connectivity
    else:
        logging.error(
            'Uploader settings invalid or server isn\'t configured, contact [email protected]'
        )
        sys.exit(1)

    # FIXME need to validate remote_config, config

    logging.info('Starting upload watcher')
    watcher_thread = WatcherThread(CONFIG.get('watch_dir'), trigger_upload)
    watcher_thread.finished.connect(app.exit)
    watcher_thread.start()

    logging.info('Starting heartbeat thread')
    heartbeat_thread = HeartbeatThread(appctxt, remote_config, CONFIG,
                                       upload_missing_files)
    heartbeat_thread.finished.connect(app.exit)
    heartbeat_thread.start()

    worker_threads = []
    for i in range(appctxt.build_settings['n_upload_worker_threads']):
        logging.info(f'Starting worker {i}')
        worker_thread = WorkerThread(appctxt, remote_config, CONFIG,
                                     UPLOAD_QUEUE)
        worker_thread.finished.connect(app.exit)
        worker_thread.start()
        worker_threads.append(worker_thread)

    #def excepthook(exc_type, exc_value, exc_tb):
    #    import traceback
    #    tb = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
    #    logging.error("error caught: %s", str(tb))
    #    capture_exception(exc_type)
    #sys.excepthook = excepthook

    exit_code = -1
    delay = 2
    for i in range(5):
        logging.info('Starting')
        exit_code = app.exec_()
        if exit_code == 0:
            break
        logging.info(f'Exit loop {exit_code}, sleeping {delay}')
        time.sleep(delay)
        delay = delay**2

    logging.info(f'Exited: {exit_code}')
    sys.exit(exit_code)
Beispiel #34
0
        self.statusBar().addWidget(download_widget)

    def _remove_download_requested(self):
            download_widget = self.sender()
            self.statusBar().removeWidget(download_widget)
            del download_widget

    def _show_find(self):
        if self._find_tool_bar is None:
            self._find_tool_bar = FindToolBar()
            self._find_tool_bar.find.connect(self._tab_widget.find)
            self.addToolBar(Qt.BottomToolBarArea, self._find_tool_bar)
        else:
            self._find_tool_bar.show()
        self._find_tool_bar.focus_find()

    def write_bookmarks(self):
        self._bookmark_widget.write_bookmarks()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_win = create_main_window()
    initial_urls = sys.argv[1:]
    if not initial_urls:
        initial_urls.append('http://qt.io')
    for url in initial_urls:
        main_win.load_url_in_new_tab(QUrl.fromUserInput(url))
    exit_code = app.exec_()
    main_win.write_bookmarks()
    sys.exit(exit_code)
Beispiel #35
0
def test():
    app = QApplication()
    # data = XAnlageV_Zeile_Data( 1, "Name", "Kendel", "Name des Steuerpflichtigen" )
    # z = AnlageV_ZeileView( data )
    # z.show()
    app.exec_()
Beispiel #36
0
def main():
    app = QApplication([])
    rig = Rigctl()
    rig.show()
    app.exec_()
Beispiel #37
0
def main():
    app = QApplication(sys.argv)
    window = GuiClass()
    window.show()
    app.exec_()
Beispiel #38
0
def main():
    app = QApplication(sys.argv)
    memory_test_controller = MemoryTestController()
    memory_test_controller.ui.show()
    sys.exit(app.exec_())
Beispiel #39
0
        self.setGeometry(150, 150, 350, 350)

        self.UI()

    def UI(self):
        self.widgets()
        self.layouts()

    def widgets(self):
        self.button = QPushButton("Button")

        self.checkbox = QCheckBox()

    def layouts(self):
        self.main_layout = QHBoxLayout()

        self.main_layout.addWidget(self.button)
        self.main_layout.addWidget(self.checkbox)

        self.setLayout(self.main_layout)



if __name__ == "__main__":
    MainEventThread = QApplication([])

    MainApplication = Main()
    MainApplication.show()

    sysExit(MainEventThread.exec_())
Beispiel #40
0
def test2():
    app = QApplication()
    v = TestView()
    v.setWindowTitle("Test")
    v.show()
    app.exec_()
Beispiel #41
0
def test():
    app = QApplication()
    v = IccTableEditorView()
    v.setWindowTitle("Test zum Testen")
    v.show()
    app.exec_()
Beispiel #42
0
    def collapse(self, full_rows: list):
        for row in reversed(sorted(full_rows)):
            for column in range(self.num_columns):
                self[row, column].collapse()

    def shift(self, full_rows: list):
        for row in reversed(range(min(full_rows))):
            for column in range(self.num_columns):
                if self[row, column] is not None:
                    self[row, column].shift(len(full_rows))

    def restart(self):
        for tile in filter(lambda tl: tl is not None, self):
            tile.disappear()
        self.clear()
        self.update({(row, column): None for row in range(self.num_rows) for column in range(self.num_columns)})
        self.score = 0
        self.delegate.scored(self.score)
        self.spawn()


if __name__ == '__main__':
    from PySide2.QtWidgets import QApplication
    import sys
    import ui

    application = QApplication(sys.argv)
    qTetris = ui.QTetris()
    sys.exit(application.exec_())
Beispiel #43
0
    Batch.signals.batch_inactive.connect(mwi.setFullWindow)

    for Thread in Thread_List:
        mwi.signals.windowClosing.connect(Thread.close)

    ##########################
    ## --- Thread start --- ##
    ##########################

    ## Start threads
    Cam_Capturestream.start(QThread.HighPriority)
    Image_Processor.start(QThread.HighPriority)

    ########################
    ## --- Exit stuff --- ##
    ########################

    ret = app.exec_()

    print("Main function thread: " + str(QThread.currentThread()))
    ## Make sure positioning is stopped
    for Thread in Thread_List:
        if Thread is not None:
            Thread.wait_ms(1000)
            print("waiting for Thread: " + str(Thread) + " to exit.")

    ## stops the motors and disconnects from pseudo serial link /tmp/printer at exit
    steppers.PrintHAT_serial.disconnect()

    sys.exit(ret)
Beispiel #44
0
    #get all ip adresses in the lan
    host_list = get_neighbors()
    print(host_list)

    col_getter = [  {"Name": "Dev", "Getter": lambda aHostItem: aHostItem["dev"]},
                    {"Name": "Ip", "Getter": lambda aHostItem: aHostItem["ip"]},
                    {"Name": "Mac", "Getter": lambda aHostItem: aHostItem["mac"]}, ]


    host_table = QTableView()
    host_model = HostModel(host_list, col_getter, host_table)
    host_table.setModel(host_model)
    host_table.show()

    # Run the main Qt loop
    sys.exit(app.exec_())














Beispiel #45
0
def main():

    if parser.lang:
        sys_locale = parser.lang[0]
    else:
        sys_locale = QtCore.QLocale.system().name()
    translator = QtCore.QTranslator()

    #load intern dialogs translations
    qtTranslator = QtCore.QTranslator()
    qtTranslator.load("qt_" + sys_locale, QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath))

    #load translations files
    translations_path = os.path.join(os.getenv("PINGUINO_LIB"), "multilanguage")
    trasnlations = os.path.exists(translations_path)

    if trasnlations and (os.getenv("PINGUINO_MODE") == "NORMAL"):
        translations_file = "pinguino_" + sys_locale

        if translations_file + ".qm" in os.listdir(translations_path):
            translator.load(os.path.join(os.getenv("PINGUINO_LIB"), "multilanguage", "pinguino_{}.qm".format(sys_locale)))

        elif "_" in sys_locale:
            sys_locale = sys_locale[:sys_locale.find("_")]
            translations_file = "pinguino_" + sys_locale
            if translations_file + ".qm" in os.listdir(translations_path):
                translator.load(os.path.join(os.getenv("PINGUINO_LIB"), "multilanguage", "pinguino_{}.qm".format(sys_locale)))

    app = QApplication(sys.argv)

    #Splash (pinguino\qtgui\resources\art)
    #pixmap = QPixmap(":/logo/art/splash.png")
    pixmap = QPixmap("pinguino/qtgui/resources/art/splash.png")
    #pixmap = QPixmap("pinguino/qtgui/resources/art/pinguino_logo_background_blue-256x256.png")
    #pixmap = QPixmap(760, 256)
    #pixmap.fill(QtGui.QColor("#4d4d4d"))
    # keep the splash screen above all the other windows on the desktop
    splash = QSplashScreen(pixmap, QtCore.Qt.WindowStaysOnTopHint)

    splash.show()
    splash.setStyleSheet("""
        font-family: inherit;
        font-weight: normal;
        font-size: 11pt;
        """)

    # update the splash screen with messages
    def splash_write(msg):
        if not splash is None:
            splash.showMessage("\t" + msg, color=QtGui.QColor("#4d4d4d"), alignment=QtCore.Qt.AlignBottom)

    splash_write(NAME + " " + MAJOR)
    app.processEvents()

    app.installTranslator(qtTranslator)
    if trasnlations:
        app.installTranslator(translator)

    frame = PinguinoIDE(splash_write=splash_write)
    frame.show()

    if not splash is None:
        splash.finish(frame)

    app.exec_()