예제 #1
0
def main():
    print(f'PySide6=={PySideVer} Qt=={QtVer}')

    parser = ArgumentParser(
        description='cappuccino: Simple image viewer with download')
    parser.add_argument('download_keyword',
                        nargs='?',
                        default='',
                        help='image keyword to download')
    args = parser.parse_args()

    download_keyword = args.download_keyword
    if not download_keyword and not exist_images():
        download_keyword = DEFAULT_KEYWORD

    initialize_qt()

    app = QGuiApplication(sys.argv)
    app.setWindowIcon(QIcon(resource_path('cappuccino.ico')))

    is_download = download_keyword != ''
    mmodel = MainModel(is_download, IMAGES_DIR_NAME)
    dmodel = DownloaderModel(download_keyword, IMAGES_DIR_NAME)
    imodel = ImageViewerModel(IMAGES_DIR_NAME)
    dmodel.download_completed.connect(mmodel.on_download_completed)

    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty('mmodel', mmodel)
    engine.rootContext().setContextProperty('dmodel', dmodel)
    engine.rootContext().setContextProperty('imodel', imodel)
    engine.load(f'file:///{resource_path("qml/Main.qml")}')

    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec())
예제 #2
0
파일: ui.py 프로젝트: seimsel/signals
    def start(self):
        qt_app = QGuiApplication([])
        qt_app.aboutToQuit.connect(self._app.stop)
        qml_engine = QQmlApplicationEngine(qt_app)

        for plugin in self._app._plugin_registry.plugins.values():
            if not hasattr(plugin, "after_qml_engine_created"):
                continue

            plugin.after_qml_engine_created(qml_engine)

        controller = Controller(qml_engine, self._app)
        qml_engine.rootContext().setContextProperty("controller", controller)
        qml_engine.load(str(self._app.base_directory / "ui/qml/main.qml"))

        qt_app.exec_()
예제 #3
0
def main_app(base_path, file, file_config):
    """Run the GUI of xBan

    The function initiates and resize the application
    """
    app = QApplication(sys.argv)

    if hasattr(QStyleFactory, "AA_UseHighDpiPixmaps"):
        app.setAttribute(Qt.AA_UseHighDpiPixmaps)

    with open(os.path.join(base_path, "xBanStyle.css"), "r") as style_sheet:
        style = style_sheet.read()

    app.setWindowIcon(QIcon(os.path.join(base_path, "xBanUI.png")))
    xBanApp = xBanWindow(base_path, file, file_config)

    xBanApp.setStyleSheet(style)

    # resize and move screen to center

    primary_screen = QGuiApplication.primaryScreen()
    if primary_screen:
        screen_size = primary_screen.availableSize()

        xBanApp.resize(screen_size.width() / 3, screen_size.height() / 2)
        xBanApp.move(
            (screen_size.width() - xBanApp.width()) / 2,
            (screen_size.height() - xBanApp.height()) / 2,
        )

        app.setStyle("Fusion")
        sys.exit(app.exec_())

    else:
        main_logger.error("Primary screen not found")
예제 #4
0
파일: app.py 프로젝트: rubbieKelvin/paper
def main():
    app = QGuiApplication(sys.argv)
    app.setApplicationName(metadata.get("Name"))

    # QQuickStyle.setStyle("Material")
    QmlEncryptedJSONStorage6.DICTIONARY = {"$apphome": home}

    engine = Paper()
    encryptedStorage = QmlEncryptedJSONStorage6()
    encryptedStorage._key = 26

    engine.rootContext().setContextProperty("encryptedStorage",
                                            encryptedStorage)
    engine.init_ui()

    sys.exit(app.exec_())
def screen_info(widget):
    """Format information on the screens"""
    policy = QGuiApplication.highDpiScaleFactorRoundingPolicy()
    policy_string = str(policy).split('.')[-1]
    result = "<p>High DPI scale factor rounding policy: {}</p><ol>".format(
        policy_string)
    for screen in QGuiApplication.screens():
        current = screen == widget.screen()
        result += "<li>"
        if current:
            result += "<i>"
        result += '"{}" {} {}DPI, DPR={}'.format(
            screen.name(), format_geometry(screen.geometry()),
            int(screen.logicalDotsPerInchX()), screen.devicePixelRatio())
        if current:
            result += "</i>"
        result += "</li>"
    result += "</ol>"
    return result
예제 #6
0
 def initUI(self):
     # setup UI
     self.setWindowTitle("Taplist - Let's Beer Brewpub")
     # get screen width and height
     self.screen = QGuiApplication.primaryScreen().geometry()
     self.width = self.screen.width()
     self.height = self.screen.height()
     # set screen size
     self.resize(1920, 1080)
     # self.setMinimumWidth(800)
     self.layout = QGridLayout()
예제 #7
0
    def __init__(self):
        super(MainWindow, self).__init__()

        self.setWindowTitle('Qt DataVisualization 3D Bars')

        self.bars = Q3DBars()

        self.columnAxis = QCategory3DAxis()
        self.columnAxis.setTitle('Columns')
        self.columnAxis.setTitleVisible(True)
        self.columnAxis.setLabels(['Column1', 'Column2'])
        self.columnAxis.setLabelAutoRotation(30)

        self.rowAxis = QCategory3DAxis()
        self.rowAxis.setTitle('Rows')
        self.rowAxis.setTitleVisible(True)
        self.rowAxis.setLabels(['Row1', 'Row2'])
        self.rowAxis.setLabelAutoRotation(30)

        self.valueAxis = QValue3DAxis()
        self.valueAxis.setTitle('Values')
        self.valueAxis.setTitleVisible(True)
        self.valueAxis.setRange(0, 5)

        self.bars.setRowAxis(self.rowAxis)
        self.bars.setColumnAxis(self.columnAxis)
        self.bars.setValueAxis(self.valueAxis)

        self.series = QBar3DSeries()
        self.arrayData = [[1, 2], [3, 4]]
        self.series.dataProxy().addRows(dataToBarDataArray(self.arrayData))

        self.bars.setPrimarySeries(self.series)

        self.container = QWidget.createWindowContainer(self.bars)

        if not self.bars.hasContext():
            print("Couldn't initialize the OpenGL context.")
            sys.exit(-1)

        camera = self.bars.scene().activeCamera()
        camera.setYRotation(22.5)

        geometry = QGuiApplication.primaryScreen().geometry()
        size = geometry.height() * 3 / 4
        self.container.setMinimumSize(size, size)

        self.container.setSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)
        self.container.setFocusPolicy(Qt.StrongFocus)
        self.setCentralWidget(self.container)
예제 #8
0
파일: ui.py 프로젝트: roadroot/chess
 def initialize(self):
     screen = QGuiApplication.primaryScreen().size()
     size = screen.height() * 0.7
     self.window = QMainWindow()
     self.window.setAutoFillBackground(True)
     self.window.setWindowFlag(
         PySide6.QtCore.Qt.WindowType.WindowMaximizeButtonHint, False)
     self.window.setWindowTitle('Chess')
     self.window.resize(size, size)
     self.window.move((screen.width() - self.window.width()) // 2,
                      (screen.height() - self.window.height()) // 2)
     self.window.show()
     self.margin = 10
     self.button_size = (size - 2 * self.margin) // 8
예제 #9
0
    def main(self):
        init()
        # Welcome users, and load configurations.
        try:
            _, self._noupdate, self._config = canvas_grab.get_options.get_options(
            )
        except TypeError:
            # User canceled the configuration process
            return

        app = QGuiApplication(sys.argv)
        app.setQuitOnLastWindowClosed(True)
        app.aboutToQuit.connect(self._exit_handler)
        engine = QQmlApplicationEngine()
        engine.rootContext().setContextProperty('py_sync_model', self._model)
        engine.load(os.path.join(os.path.dirname(__file__), "ui/main.qml"))

        if not engine.rootObjects():
            sys.exit(-1)

        thread = threading.Thread(target=self._canvas_grab_run)
        thread.start()

        sys.exit(app.exec_())
예제 #10
0
def main(argv: List[str]):
    config = Config(Path(argv[1]))

    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()

    # Instance of the Python object
    backend = Backend(CoreApp(iter_files(Path('.'), config.exceptions), config.root_folder, config.root_category))

    # Expose the Python object to QML
    context = engine.rootContext()
    context.setContextProperty('backend', backend)

    #qmlRegisterType(Test, 'TestTypes', 1, 0, 'Test')

    # Get the path of the current directory, and then add the name
    # of the QML file, to load it.
    qmlFile = join(dirname(__file__), 'qml', 'main.qml')
    engine.load(abspath(qmlFile))

    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())
예제 #11
0
    def update(self):
        grid_unit = QFontMetrics(
            QGuiApplication.font()).boundingRect('M').height()

        if grid_unit % 2 != 0:
            grid_unit += 1

        if grid_unit != self._grid_unit:
            self._grid_unit = grid_unit
            self._changed_grid_unit.emit(self._grid_unit)

        if grid_unit != self._large_spacing:
            self._small_spacing = max(2, int(
                grid_unit / 4))  # 1 / 4 of grid_unit, at least 2
            self._large_spacing = self._small_spacing * 2
            self._changed_spacing.emit()
예제 #12
0
    def update_device_pixel_ratio(self):
        # Using QGuiApplication::devicePixelRatio() gives too coarse values,
        # i.e.it directly jumps from 1.0 to 2.0.  We want tighter control on
        # sizing, so we compute the exact ratio and use that.
        # TODO: make it possible to adapt to the dpi for the current screen dpi
        #   instead of assuming that all of them use the same dpi which applies for
        #   X11 but not for other systems.

        primary = QGuiApplication.primaryScreen()
        if primary:
            return

        dpi = primary.logicalDotsPerInchX()
        # Usual "default" is 96 dpi
        # that magic ratio follows the definition of "device independent pixel" by Microsoft
        self._device_pixel_patio = dpi / 96
        self._changed_spacing.emit()
예제 #13
0
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.userInfo = None
        self.setupUi(self)
        self.setWindowTitle("Waifu2x-Gui")
        self.msgForm = QtBubbleLabel(self)
        self.settingForm = QtSetting(self)
        self.settingForm.hide()
        self.settingForm.LoadSetting()

        self.aboutForm = QtAbout(self)
        self.img = QtImg()
        self.stackedWidget.addWidget(self.img)
        # self.resize(1000, 1000)
        self.menuabout.triggered.connect(self.OpenAbout)
        desktop = QGuiApplication.primaryScreen().geometry()
예제 #14
0
    def __init__(self):

        super(Ruler, self).__init__()

        self.old_position = None  # is used for dragging of the window
        self.setMinimumWidth(50)
        self.setMinimumHeight(50)

        # load the options
        self.data = Data()

        # main widget
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.constructContextMenu)

        self.setWindowTitle('Screen Ruler')
        self.resize(self.data.get('ruler_width'),
                    self.data.get('ruler_height'))
        self.setMouseTracking(True)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.setGeometry(
            QStyle.alignedRect(
                Qt.LeftToRight, Qt.AlignCenter, self.size(),
                QGuiApplication.primaryScreen().availableGeometry()))

        windowFlags = Qt.CustomizeWindowHint | Qt.FramelessWindowHint

        leftResize = SizeGrip(self, True)
        rightResize = SizeGrip(self, False)

        self.left_resize = leftResize
        self.right_resize = rightResize

        if self.data.get('always_above'):
            windowFlags = windowFlags | Qt.WindowStaysOnTopHint
        self.setWindowFlags(
            windowFlags)  # Turns off the default window title hints

        # initialize the secondary windows
        self.about_window = AboutWindow()
        self.options_window = OptionsWindow(self)

        if self.data.get('options_opened'):
            self.openOptions()
예제 #15
0
def create_app_engine(argv, qml_file):
    # We only support EGL but Qt still uses the legacy GLX by default
    os.environ["QT_XCB_GL_INTEGRATION"] = "xcb_egl"

    # We do not support Opengl 2.1 contexts (the default on macOS), so we
    # force OpenGL 4.1 (Core Profile)
    if platform.system() == "Darwin":
        surface_format = QSurfaceFormat()
        surface_format.setRenderableType(QSurfaceFormat.OpenGL)
        major_version, minor_version = (4, 1)
        surface_format.setVersion(major_version, minor_version)
        surface_format.setProfile(QSurfaceFormat.CoreProfile)
        surface_format.setDepthBufferSize(24)
        surface_format.setStencilBufferSize(8)
        surface_format.setAlphaBufferSize(8)
        QSurfaceFormat.setDefaultFormat(surface_format)

    app = QGuiApplication(argv)
    QQuickWindow.setGraphicsApi(QSGRendererInterface.OpenGL)
    engine = QQmlApplicationEngine(qml_file)
    engine.quit.connect(app.quit)
    return app, engine
예제 #16
0
 def __init__(self, parent, history):
     super().__init__(parent=parent)
     self.setWindowTitle("History")
     layout = QVBoxLayout()
     text = QPlainTextEdit()
     font = QFont()
     font.setFamily("monospace")
     font.setStyleHint(QFont.Monospace)
     text.setFont(font)
     highlighter = PythonHighlighter(text.document())  # noqa: F841
     text.setReadOnly(True)
     text.setPlainText(history)
     layout.addWidget(text)
     buttonbox = QDialogButtonBox(QDialogButtonBox.Ok)
     clipboardbutton = QPushButton("Copy to clipboard")
     buttonbox.addButton(clipboardbutton, QDialogButtonBox.ActionRole)
     clipboard = QGuiApplication.clipboard()
     clipboardbutton.clicked.connect(
         lambda: clipboard.setText(history + "\n"))
     layout.addWidget(buttonbox)
     self.setLayout(layout)
     buttonbox.accepted.connect(self.accept)
     self.resize(700, 500)
예제 #17
0
            events = i.event_gen(yield_nones=False, timeout_s=1)

            reload = False
            for event in list(events):
                (_, type_names, path, filename) = event

                if filename[-3:] == 'qml' and 'IN_MODIFY' in type_names:
                    reload = True
                    break

            if reload:
                self.requestReload.emit()


if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()

    workerThread = QThread()
    workerThread.start()
    worker = Worker()
    worker.moveToThread(workerThread)

    master = Master()
    master.command.connect(worker.run)
    worker.requestReload.connect(master.reload)
    master.command.emit()

    # Stop application gracefully:
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    status = app.exec_()
예제 #18
0
            self.load_from_json(filename)

    def load_from_json(self,filename):
        """Load list of cities from given file"""
        with open(filename,encoding="utf-8") as f:
            self.city_list = json.load(f)

    def rowCount(self, parent:QtCore.QModelIndex=...) -> int:
        """ Return number of cities in the list"""
        return len(self.city_list)

    def data(self, index:QtCore.QModelIndex, role:int=...) -> typing.Any:
        """ For given index and DisplayRole return name of the selected city"""
        # Return None if the index is not valid
        if not index.isValid():
            return None
        # If the role is the DisplayRole, return name of the city
        if role == QtCore.Qt.DisplayRole:
            return self.city_list[index.row()]["muniLabel"]


app = QGuiApplication(sys.argv)
view = QQuickView()
url = QUrl(VIEW_URL)
citylist_model = CityListModel(CITY_LIST_FILE)
ctxt = view.rootContext()
ctxt.setContextProperty('cityListModel',citylist_model)
view.setSource(url)
view.show()
app.exec_()
예제 #19
0
 def copy(self):
     QGuiApplication.clipboard().setText(self.fileNameLabel.text())
예제 #20
0
        self._name = value

    colorChanged = Signal()
    color = Property(QColor, getColor, setColor, notify=colorChanged)
    name = Property(str, getName, setName)
    chartCleared = Signal()

    @Slot()  # This should be something like @Invokable
    def clearChart(self):
        self.setColor(Qt.transparent)
        self.update()
        self.chartCleared.emit()


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

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

    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    qmlFile = os.path.join(os.path.dirname(__file__), 'app.qml')
    view.setSource(QUrl.fromLocalFile(os.path.abspath(qmlFile)))
    if view.status() == QQuickView.Error:
        sys.exit(-1)
    view.show()
    res = app.exec_()
    # Deleting the view before it goes out of scope is required to make sure all child QML instances
    # are destroyed in the correct order.
    del view
    sys.exit(res)
예제 #21
0
        if (self.staticUser.lower() == getUser.lower()
                and self.staticPass == getPass):
            # Send User And Pass
            self.signalUser.emit("Username: "******"Password: "******"Login passed!")
        else:
            self.signalLogin.emit(False)
            print("Login error!")


# INSTACE CLASS
if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()

    # Get Context
    main = MainWindow()
    engine.rootContext().setContextProperty("backend", main)

    # Load QML File
    engine.load(os.path.join(os.path.dirname(__file__), "qml/main.qml"))

    # Check Exit App
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())
예제 #22
0
 def center(self):
     qr = self.frameGeometry()
     cp = QGuiApplication.primaryScreen().availableGeometry().center()
     qr.moveCenter(cp)
     self.move(qr.topLeft())
예제 #23
0
import sys

from PySide6.QtGui import QGuiApplication, QIcon
from PySide6.QtQml import QQmlApplicationEngine

from backend import BackEnd
import resources_rc

app = QGuiApplication(sys.argv)
app.setWindowIcon(QIcon(r"icons\icon.ico"))

backend = BackEnd(app)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')
engine.rootContext().setContextProperty('backend', backend)

sys.exit(app.exec())
예제 #24
0
def initialize_qt():
    sys.argv += ['--style', 'Material']

    QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
    QCoreApplication.setAttribute(Qt.AA_UseOpenGLES)
예제 #25
0
import os
from PySide6.QtQml import qmlRegisterType  #, qmlRegisterUncreatableType
from PySide6.QtQuick import QQuickView
import re, sys
from PySide6.QtGui import QGuiApplication, QCursor
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtCore import Qt
from fileio import FileIO
from Rem import Re
from syntaxhighlighter import syntaxhighlighter

if __name__ == '__main__':
    app = QGuiApplication()

    os.environ['XCURSOR_SIZE'] = '64'
    # app.setOverrideCursor(QCursor("/home/minhinc/tmp/example/imageviewer/mycursor.png"))

    qmlfile = sys.argv[1] if len(
        sys.argv) > 1 else re.sub(r'^(.*)[.]py$', r'\1', sys.argv[0]) + '.qml'
    qmlRegisterType(FileIO, "FileIOPlugin", 1, 0, "FileIO")
    qmlRegisterType(syntaxhighlighter, "SyntaxHighlighter", 1, 0,
                    "SyntaxHighlighter")
    reinstance = Re()
    # if re.search(r'(?:\w+)?Window\s*{',open(qmlfile).read()):
    if re.search(r'^(?<!//)\s*(?:\w+)?Window\s*{\s*$',
                 open(qmlfile).read(),
                 flags=re.MULTILINE) and (
                     not re.search(r'/[*](?![*]/)*?\n\s*(?:\w+)?Window\s*{',
                                   open(qmlfile).read(),
                                   flags=re.DOTALL)
                     or re.search(r'[*]/(?!/[*])*?\n\s*(?:\w+)?Window\s*{',
예제 #26
0
#!/usr/bin/python
# This Python file uses the following encoding: utf-8
import sys
import os

from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
from PySide6 import QtCore, QtWidgets
# created from /usr/lib/qt6/rcc -g python qml.qrc -o resources.py
# converts the resources to bytes and can be called from qrc:/some/file.jpg
import resources


if __name__ == "__main__":
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)
    app = QGuiApplication(sys.argv)
    app.setApplicationName("WeatherWidget")
    app.setOrganizationName("AllspiceInc")
    app.setOrganizationDomain("AllspiceInc")
    engine = QQmlApplicationEngine()
    engine.load(QtCore.QUrl("main.qml"))

    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec())
예제 #27
0
and explains in which circumstances it is handy to use this control.
"""

import os
import sys
import platform

from PySide6.QtGui import QGuiApplication, QIcon
from PySide6.QtCore import QSettings, QUrl
from PySide6.QtQml import QQmlApplicationEngine, QQmlContext
from PySide6.QtQuickControls2 import QQuickStyle

import rc_gallery

if __name__ == "__main__":
    QGuiApplication.setApplicationName("Gallery")
    QGuiApplication.setOrganizationName("QtProject")

    app = QGuiApplication()
    QIcon.setThemeName("gallery")

    settings = QSettings()
    if not os.environ.get("QT_QUICK_CONTROLS_STYLE"):
        QQuickStyle.setStyle(settings.value("style", str))

    engine = QQmlApplicationEngine()

    built_in_styles = ["Basic", "Fusion", "Imagine", "Material", "Universal"]
    if platform.system() == "Darwin":
        built_in_styles.append("macOS")
    elif platform.system() == "Windows":