def start(): app = QGuiApplication(sys.argv) ui = DefaultUI() ui.gamesList.gameChanged.connect(test2) ui.platformSelector.platformChanged.connect(test) ui.show() sys.exit(app.exec_())
def __init__(self, qml): app = QGuiApplication(sys.argv) model = QmlModel() model.register() qmlUrl = QUrl(qml) assert qmlUrl.isValid() print(qmlUrl.path()) # assert qmlUrl.isLocalFile() """ Create an engine a reference to the window? window = QuickWindowFactory().create(qmlUrl=qmlUrl) window.show() # visible """ engine = QQmlApplicationEngine() """ Need this if no stdio, i.e. Android, OSX, iOS. OW, qWarnings to stdio. engine.warnings.connect(self.errors) """ engine.load(qmlUrl) engine.quit.connect(app.quit) app.exec_() # !!! C exec => Python exec_ print("Application returned")
def main(): print("start") app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() engine.load(QUrl("main.qml")) engine.rootObjects()[0].show() sys.exit(app.exec_())
def main(): app = QGuiApplication(sys.argv) qmlRegisterType(MainController, 'MainController', 1, 0, 'MainController') qmlRegisterType(ProfileViewModel, 'ProfileViewModel', 1, 0, 'ProfileViewModel') engine = QQmlApplicationEngine() main_controller = MainController() main_controller.profile_selection_changed(0) engine.rootContext().setContextProperty('mainController', main_controller) engine.load(QUrl.fromLocalFile(pkg_resources.resource_filename('yarg.resource', 'main.qml'))) sys.exit(app.exec_())
def onClipboardChanged(self, mode): if mode == QClipboard.Clipboard: if not QGuiApplication.clipboard().ownsClipboard(): self.clipboardTimer.start() else: self.clipboardTimer.stop() elif mode == QClipboard.Selection: if not QGuiApplication.clipboard().ownsSelection(): self.selectionTimer.start() else: self.selectionTimer.stop()
def handle_click(self, reason): if reason != QSystemTrayIcon.Trigger: return QGuiApplication.primaryScreen().grabWindow(0).save('scr.jpg', 'jpg') ssh = SSHClient() ssh.load_system_host_keys() ssh.connect(hostname=self.ssh_hostname, port=self.ssh_port, username=self.ssh_username) scp = SCPClient(ssh.get_transport()) dest_name = time.strftime("screenshot_%Y%m%d_%H%M%S.jpg", time.localtime()) scp.put('scr.jpg', self.ssh_remote_path + '/' + dest_name)
def setGrabbing(self, grabbing): if(self._grabbing != grabbing): self._grabbing = grabbing if(self._grabbing): self.installEventFilter(self._colorPickingEventFilter) QGuiApplication.setOverrideCursor(QCursor(QtCore.Qt.CrossCursor)) self.grabMouse() else: self.ungrabMouse() self.removeEventFilter(self._colorPickingEventFilter) QGuiApplication.restoreOverrideCursor() self.grabbingChanged.emit()
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_size_changed.connect(self._controller.window_resize) 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 updateCurrentColor(self): cursorPos = QCursor.pos() # Catch the pixel pointed by the mouse on a pixmap pixmap = QGuiApplication.screens()[self._desktop.screenNumber()].grabWindow(self._desktop.winId(), cursorPos.x(), cursorPos.y(), 1, 1) qImage = pixmap.toImage() qColor = QColor(qImage.pixel(0, 0)) self.setCurrentColor(qColor)
def handleCursorPositionChanged(self): cursor = self.textCursor() # update block format toolbar blockFmt = cursor.blockFormat() blockStyle = blockFmt.property(QTextFormat.UserProperty) self.updateBlockFormat.emit(blockStyle) # update text format toolbar charFmt = cursor.charFormat() # get the QTextCharFormat at the current cursor position charStyle = charFmt.property(QTextFormat.UserProperty) self.updateCharFormat.emit(charStyle) # open/close URL editor for external links if charStyle and charStyle[0] == 'link': if not (QGuiApplication.keyboardModifiers() & Qt.ControlModifier): url = charFmt.anchorHref() # get global cursor position pos = self.cursorRect() pos = pos.bottomLeft() pos = self.viewport().mapToGlobal(pos) self.l.move(pos) self.l.setUrl(url) self.l.show() else: self.l.hide()
def emitChanged(self, mode): clipboard = QGuiApplication.clipboard() mimeData = clipboard.mimeData() data = {} for format in self.formats: if mimeData.hasFormat(format): data[format] = mimeData.data(format) self.changed.emit(data)
def __init__(self, config_dict): super().__init__() self.config_dict = config_dict self.clipboard = QGuiApplication.clipboard() self.reconstruct = enable_rhc(config_dict["random_hit_chance"])( self.reconstruct ) self.clipboard.dataChanged.connect(self.reconstruct)
def main(argv): a = QGuiApplication(argv) a.setOrganizationDomain("mapeditor.org") a.setApplicationName("TmxRasterizer") a.setApplicationVersion("1.0") options = CommandLineOptions() parseCommandLineArguments(options) if (options.showVersion): showVersion() return 0 if (options.showHelp or options.fileToOpen=='' or options.fileToSave==''): showHelp() return 0 if (options.scale <= 0.0 and options.tileSize <= 0): showHelp() return 0 w = TmxRasterizer() w.setAntiAliasing(options.useAntiAliasing) w.setIgnoreVisibility(options.ignoreVisibility) w.setLayersToHide(options.layersToHide) if (options.tileSize > 0): w.setTileSize(options.tileSize) elif (options.scale > 0.0): w.setScale(options.scale) return w.render(options.fileToOpen, options.fileToSave)
def __init__(self, parent = None): super().__init__(parent) self.app = QGuiApplication.instance() self._queue = deque() self.frontendpy = parent self._listener = threading.Thread(target = self.listenerThread, daemon = True, name = "frontend communication listener") self._listener.start() tasks = sys.argv[1:] if tasks: self.createTasksAction(tasks) self.urlExtractor = UrlExtractor(self) self._clipboard = QGuiApplication.clipboard() self.app.settings.applySettings.connect(self.slotWatchClipboardToggled)
def __init__(self, parent = None): super().__init__(parent) # set cache self._cachePath = QNetworkDiskCache(self) cacheLocation = QGuiApplication.instance().settings.get("frontend", "cachelocation") self._cachePath.setCacheDirectory(cacheLocation) self._cachePath.setMaximumCacheSize(20 * 1024 * 1024) # 20M self.setCache(self._cachePath)
def main(): # Set up correct Ctrl-C behavior. signal.signal(signal.SIGINT, signal.SIG_DFL) app = QGuiApplication( sys.argv ) engine = QQmlEngine() engine.addImportPath( path.join( path.dirname( __file__ ), 'ui', 'qml' ) ) core.register_types() component = QQmlComponent( engine ) component.loadUrl( QUrl( '/home/feoh3/.config/nube/hud.qml' ) ) if component.isError(): print( "\n".join( error.toString() for error in component.errors() ) ) else: window = component.create() app.exec_()
class PillowQPixmapTestCase(PillowQtTestCase): def setUp(self): PillowQtTestCase.setUp(self) try: if ImageQt.qt_version == '5': from PyQt5.QtGui import QGuiApplication elif ImageQt.qt_version == '4': from PyQt4.QtGui import QGuiApplication elif ImageQt.qt_version == 'side': from PySide.QtGui import QGuiApplication except ImportError: self.skipTest('QGuiApplication not installed') self.app = QGuiApplication([]) def tearDown(self): PillowQtTestCase.tearDown(self) self.app.quit()
def execute_app(config_dict): # On systems running X11, possibly due to a bug, Qt fires the qWarning # "QXcbClipboard::setMimeData: Cannot set X11 selection owner" while # setting clipboard data when copy/selection events are encountered in # rapid succession, resulting in clipboard data not being set. This env # variable acts as a fail-safe which aborts the application if this # happens more than once. Similar situation arises when another clipboard # management app (like GPaste) is running alongside chaos. os.environ["QT_FATAL_WARNINGS"] = "1" signal.signal(signal.SIGTERM, qt_quit) signal.signal(signal.SIGINT, qt_quit) signal.signal(signal.SIGTSTP, qt_quit) signal.signal(signal.SIGHUP, qt_quit) app = QGuiApplication(sys.argv) timer(100, lambda: None) cb = Clipboard(config_dict) sys.exit(app.exec_())
def __init__(self, parent=None, **kwargs): super(BasePlotWidget, self).__init__(parent=parent, **kwargs) self.setActiveCurveHandling(False) self.setGraphGrid('both') # Create toolbars. self._interactiveModeToolBar = tools.toolbars.InteractiveModeToolBar( parent=self, plot=self) self.addToolBar(self._interactiveModeToolBar) self._toolBar = QToolBar('Curve or Image', parent=self) self._resetZoomAction = actions.control.ResetZoomAction( parent=self, plot=self) self._toolBar.addAction(self._resetZoomAction) self._xAxisAutoScaleAction = actions.control.XAxisAutoScaleAction( parent=self, plot=self) self._toolBar.addAction(self._xAxisAutoScaleAction) self._yAxisAutoScaleAction = actions.control.YAxisAutoScaleAction( parent=self, plot=self) self._toolBar.addAction(self._yAxisAutoScaleAction) self._gridAction = actions.control.GridAction( parent=self, plot=self) self._toolBar.addAction(self._gridAction) self._curveStyleAction = actions.control.CurveStyleAction( parent=self, plot=self) self._toolBar.addAction(self._curveStyleAction) self._colormapAction = actions.control.ColormapAction( parent=self, plot=self) self._toolBar.addAction(self._colormapAction) self._keepAspectRatio = actions.control.KeepAspectRatioAction( parent=self, plot=self) self._toolBar.addAction(self._keepAspectRatio) self.addToolBar(self._toolBar) self._outputToolBar = tools.toolbars.OutputToolBar( parent=self, plot=self) self.addToolBar(self._outputToolBar) windowHandle = self.window().windowHandle() if windowHandle is not None: self._ratio = windowHandle.devicePixelRatio() else: self._ratio = QGuiApplication.primaryScreen().devicePixelRatio() self._snap_threshold_dist = 5 self.sigPlotSignal.connect(self._plotEvent)
def _take_screenshot(self): """ Grabs the contents of screen and store it, update preview widget and show main window """ screen = QGuiApplication.instance().primaryScreen() if screen: self.screenshot = screen.grabWindow(0) self.preview_widget.set_image(self.screenshot) if not self.isVisible(): self.show()
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_())
def __init__(self, parent): super().__init__(parent) app = QGuiApplication.instance() self.setTitle("Xware Desktop with QML (experimental)") self.setResizeMode(QQuickView.SizeRootObjectToView) self.qmlUrl = QUrl.fromLocalFile(os.path.join(constants.FRONTEND_DIR, "QML/Main.qml")) self.rootContext().setContextProperty("adapters", app.adapterManager) self.rootContext().setContextProperty("taskModel", app.proxyModel) self.setSource(self.qmlUrl) self.resize(QSize(800, 600))
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 main(): app = QGuiApplication(sys.argv) app.setApplicationName('InfiniteCopy') openDataBase() view = QQuickView() clipboardItemModel = ClipboardItemModel() clipboardItemModel.create() filterProxyModel = QSortFilterProxyModel() filterProxyModel.setSourceModel(clipboardItemModel) clipboard = Clipboard() clipboard.setFormats([ mimeText, mimeHtml, mimePng, mimeSvg ]) clipboard.changed.connect(clipboardItemModel.addItem) engine = view.engine() imageProvider = ClipboardItemModelImageProvider(clipboardItemModel) engine.addImageProvider("items", imageProvider) context = view.rootContext() context.setContextProperty('clipboardItemModel', clipboardItemModel) context.setContextProperty('clipboardItemModelFilterProxy', filterProxyModel) context.setContextProperty('clipboard', clipboard) view.setSource(QUrl.fromLocalFile('qml/MainWindow.qml')) view.setGeometry(100, 100, 400, 240) view.show() engine.quit.connect(QGuiApplication.quit) return app.exec_()
def __init__(self, config, daemon, plugins): set_language(config.get('language', get_default_language())) Logger.__init__(self) # Uncomment this call to verify objects are being properly # GC-ed when windows are closed #network.add_jobs([DebugMem([Abstract_Wallet, SPV, Synchronizer, # ElectrumWindow], interval=5)]) QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) if hasattr(QtCore.Qt, "AA_ShareOpenGLContexts"): QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts) if hasattr(QGuiApplication, 'setDesktopFileName'): QGuiApplication.setDesktopFileName('vialectrum.desktop') self.gui_thread = threading.current_thread() self.config = config self.daemon = daemon self.plugins = plugins self.windows = [] self.efilter = OpenFileEventFilter(self.windows) self.app = QElectrumApplication(sys.argv) self.app.installEventFilter(self.efilter) self.app.setWindowIcon(read_QIcon("vialectrum.png")) # timer self.timer = QTimer(self.app) self.timer.setSingleShot(False) self.timer.setInterval(500) # msec self.nd = None self.network_updated_signal_obj = QNetworkUpdatedSignalObject() self._num_wizards_in_progress = 0 self._num_wizards_lock = threading.Lock() # init tray self.dark_icon = self.config.get("dark_icon", False) self.tray = QSystemTrayIcon(self.tray_icon(), None) self.tray.setToolTip('Vialectrum') self.tray.activated.connect(self.tray_activated) self.build_tray_menu() self.tray.show() self.app.new_window_signal.connect(self.start_new_window) self.set_dark_theme_if_needed() run_hook('init_qt', self)
def run(): signal.signal(signal.SIGINT, signal.SIG_DFL) app = QGuiApplication(sys.argv) view = QQuickView() view.setTitle('Hot reloading demo') qml_engine = view.rootContext().engine() qml_engine.addImportPath(lib_dir_path) notifier = HotReloadNotifier(demo_dir_path, qml_engine, parent=app) view.rootContext().setContextProperty('hotReloadNotifier', notifier) qml_url = QUrl.fromLocalFile(os.path.join(demo_dir_path, 'Demo.qml')) view.setSource(qml_url) view.show() exit_code = app.exec_() # notifier.stop() # seems like this is not needed sys.exit(exit_code)
def main(argv): signal.signal(signal.SIGINT, signal.SIG_DFL) qapp = QGuiApplication([]) engine = QQmlApplicationEngine() data_list = [] for entry in os.scandir(argv[1]): url = "file://" + urllib.parse.quote(os.path.abspath(entry.path)) digest = hashlib.md5(os.fsencode(url)).hexdigest() result = os.path.join(xdg.BaseDirectory.xdg_cache_home, "thumbnails", "normal", digest + ".png") data_list.append(Foo(entry.name, result, "2018-01-11T19:20")) engine.load(QUrl('main.qml')) ctxt = engine.rootContext() ctxt.setContextProperty("menu2", QVariant(data_list)) win = engine.rootObjects()[0] win.show() sys.exit(qapp.exec())
def __init__( self, parent ): QQuickWindow.setDefaultAlphaBuffer( True ) super().__init__( parent ) screen = QGuiApplication.instance().primaryScreen() self._resizeTo( screen.geometry() ) screen.geometryChanged.connect( self._resizeTo ) self.setFlags(Qt.BypassWindowManagerHint) self.setColor(QColor( Qt.transparent )) self._showKey = None self._keyGrabber = platform.KeyGrabber( self )
def appQWindow(self): ''' QWindow of app, or None. Needed to transientParent a QQuickView to app QWindow. ''' qwinList = QGuiApplication.topLevelWindows() #print("window count", len(qwinList)) #print(qwinList[0]) if len(qwinList)==1: result = qwinList[0] else: print("Fail to find single QWindow for app.") result = None return result
def setUp(self): PillowQtTestCase.setUp(self) try: if ImageQt.qt_version == '5': from PyQt5.QtGui import QGuiApplication elif ImageQt.qt_version == '4': from PyQt4.QtGui import QGuiApplication elif ImageQt.qt_version == 'side': from PySide.QtGui import QGuiApplication elif ImageQt.qt_version == 'side2': from PySide2.QtGui import QGuiApplication except ImportError: self.skipTest('QGuiApplication not installed') self.app = QGuiApplication([])
def copy_to_clipboard(self): text = self.text_edit.toPlainText() clip_board = QGuiApplication.clipboard() clip_board.clear(mode=clip_board.Clipboard) clip_board.setText(text, mode=clip_board.Clipboard)
def __init__(self): super(YUVviewer, self).__init__() self.ui = Ui_YUVviewer() self.ui.setupUi(self) self.setWindowTitle('YUVviewer ' + VERSION) screen = QGuiApplication.screenAt(self.mapToGlobal(QPoint(self.width()//2,0))).geometry() size = self.geometry() self.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2) self.ui.frameSizeType_ComboBox.setStyleSheet("combobox-popup: 0;") self.ui.YUVFormat_ComboBox.setStyleSheet("combobox-popup: 0;") self.ui.frameRate_ComboBox.setStyleSheet("combobox-popup: 0;") for key,value in self.frameSizeTypeDict.items(): self.ui.frameSizeType_ComboBox.insertItem(self.ui.frameSizeType_ComboBox.count(), key) if os.path.exists(os.path.join(os.environ['HOME'],'.YUVViewer')): os.mkdir(os.path.join(os.environ['HOME'],'.YUVViewer')) self.YUVviewerConfigFile = ConfigFile(os.path.join(os.environ['HOME'],'.YUVViewer','YUVViewer.xml')) if self.YUVviewerConfigFile.config_dict['frameSizeType'] == 'Other': self.ui.frameSizeType_Other_RadioButton.setChecked(True) self.ui.frameSizeType_ComboBox.setEnabled(False) self.ui.frameSize_Width_LineEdit.setText(self.YUVviewerConfigFile.config_dict['frameSize_Width']) self.ui.frameSize_Height_LineEdit.setText(self.YUVviewerConfigFile.config_dict['frameSize_Height']) else: self.ui.frameSizeType_Combo_RadioButton.setChecked(True) self.ui.frameSizeType_ComboBox.setEnabled(True) for key,value in self.frameSizeTypeDict.items(): if key == self.YUVviewerConfigFile.config_dict['frameSizeType']: self.ui.frameSizeType_ComboBox.setCurrentText(self.YUVviewerConfigFile.config_dict['frameSizeType']) self.ui.frameSize_Width_LineEdit.setText(value[0]) self.ui.frameSize_Width_LineEdit.setFocusPolicy(QtCore.Qt.NoFocus) self.YUVviewerConfigFile.config_dict['frameSize_Width'] = value[0] self.ui.frameSize_Height_LineEdit.setText(value[1]) self.ui.frameSize_Height_LineEdit.setFocusPolicy(QtCore.Qt.NoFocus) self.YUVviewerConfigFile.config_dict['frameSize_Height'] = value[1] break currentIndex = 0 for key,value in self.YUVFormat_list.items(): if key == self.YUVviewerConfigFile.config_dict['YUVFormat']: color_list = value break currentIndex += 1 self.ui.YUVFormat_ComboBox.setCurrentIndex(currentIndex) self.updateUiSvg(color_list) frameRate_list = ['30', '60', '120'] currentIndex = frameRate_list.index(self.YUVviewerConfigFile.config_dict['frameRate']) self.ui.frameRate_ComboBox.setCurrentIndex(currentIndex) self.ui.startFrame_LineEdit.setText(self.YUVviewerConfigFile.config_dict['startFrame']) self.ui.endFrame_LineEdit.setText(self.YUVviewerConfigFile.config_dict['endFrame']) self.ui.YUVFormat_ComboBox.currentTextChanged.connect(self.changeFormat) self.ui.frameSizeType_Combo_RadioButton.clicked.connect(self.configComboBox) self.ui.frameSizeType_Other_RadioButton.clicked.connect(self.configOther) self.ui.frameSizeType_ComboBox.currentTextChanged.connect(self.changeFrameSizeType) self.ui.frameSize_Height_LineEdit.textEdited.connect(self.frameSizeHeightValidator) self.ui.frameSize_Width_LineEdit.textEdited.connect(self.frameSizeWidthValidator) self.ui.startFrame_LineEdit.textEdited.connect(self.startFrameValidator) self.ui.endFrame_LineEdit.textEdited.connect(self.endFrameValidator) self.ui.exchange_PushButton.clicked.connect(self.exchaneSize) self.ui.openFile_PushButton.clicked.connect(self.openFile) self.ui.openFolder_PushButton.clicked.connect(self.openFolder) self.ui.about_PushButton.clicked.connect(self.about) self.ui.help_PushButton.clicked.connect(self.help)
# -*- coding: utf-8 -*- from PyQt5.QtCore import QUrl,QTranslator from PyQt5.QtGui import QGuiApplication from PyQt5.QtQuick import QQuickView from PyQt5.QtQml import QQmlApplicationEngine import sys if __name__ == '__main__': path = 'main.qml' # 加载的QML文件 try: app = QGuiApplication([]) engine = QQmlApplicationEngine() trans = QTranslator() trans.load("zh_CN") app.installTranslator(trans) print(1111111111111) engine.retranslate() engine.load(QUrl(path)) app.exec() except Exception as e: print(e) sys.exit()
def my_message_output(type, context, msg): if type == QtDebugMsg: print("Debug: {} ({}:{}, {})".format(msg, context.file, context.line, context.function)) elif type == QtInfoMsg: print("Info: {} ({}:{}, {})".format(msg, context.file, context.line, context.function)) elif type == QtWarningMsg: print("Warning: {} ({}:{}, {})".format(msg, context.file, context.line, context.function)) elif type == QtCriticalMsg: print("Critical: {} ({}:{}, {})".format(msg, context.file, context.line, context.function)) elif type == QtFatalMsg: print("Fatal: {} ({}:{}, {})".format(msg, context.file, context.line, context.function)) if __name__ == '__main__': QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling) app = QApplication(sys.argv) app.setQuitOnLastWindowClosed(True) with open(os.path.join(os.path.dirname(__file__), "app.css"), "r") as style_sheet_file: app.setStyleSheet(style_sheet_file.read()) qInstallMessageHandler(my_message_output) qDebug("Message handler test") mw = MainWindow() mw.show() app.exec_()
@name.setter def name(self, name): self._name = name def __init__(self, parent=None): super(PieChart, self).__init__(parent) self._pieSlice = None self._name = '' if __name__ == '__main__': import os import sys app = QGuiApplication(sys.argv) qmlRegisterType(PieChart, "Charts", 1, 0, "PieChart") qmlRegisterType(PieSlice, "Charts", 1, 0, "PieSlice") view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) view.setSource( QUrl.fromLocalFile( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'app.qml'))) view.show() sys.exit(app.exec_())
__author__ = 'ipetrash' from typing import Union import sys from pathlib import Path sys.path.append('..') from Good_text_foreground_color_for_a_given_background_color import get_good_text_foreground_color from PyQt5.QtGui import QGuiApplication, QPainter, QImage, QColor, QFont, QFontMetrics from PyQt5.QtCore import Qt, QByteArray, QBuffer, QIODevice APP = QGuiApplication([]) SIZE = 300 RADIUS = 20 FAMILY_FONT = 'Courier New' # Need monospaced def get_optimal_font(family_font: str, w, h, text: str) -> QFont: font = QFont(family_font) font.setStyleHint(QFont.Courier, QFont.PreferAntialias) metrics = QFontMetrics(font) # SOURCE: https://github.com/gil9red/SimplePyScripts/blob/add91e36e1ee59b3956b9fafdcffc9f4ff10ed3d/qt__pyqt__pyside__pyqode/pyqt__QPainter__draw_table.py#L98 factor = w / metrics.boundingRect(0, 0, w, h, Qt.AlignCenter, text).width() if factor < 1 or factor > 1.25: font.setPointSizeF(font.pointSizeF() * factor)
import os, sys from PyQt5.QtCore import Qt, QRectF, QByteArray, QBuffer from PyQt5.QtGui import QImage, QPainter, QGuiApplication from PyQt5.QtSvg import QSvgRenderer rootdir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) srcdir = os.path.join(rootdir, 'src') icondir = os.path.join(rootdir, 'icon') app = QGuiApplication(sys.argv) icons = [] svg_extrasmall = QSvgRenderer(os.path.join(icondir, 'tuna_extrasmall.svg')) svg_small = QSvgRenderer(os.path.join(icondir, 'tuna_small.svg')) svg_big = QSvgRenderer(os.path.join(icondir, 'tunacan.svg')) for size in (16, 24, 32, 48, 64, 128, 1024): print('generate: %d' % size) if size <= 24: renderer = svg_extrasmall elif size <= 64: renderer = svg_small else: renderer = svg_big img = QImage(size, size, QImage.Format_ARGB32) img.fill(Qt.transparent) painter = QPainter(img) renderer.render(painter, QRectF(0, 0, size, size)) painter.end()
#!/usr/bin/python3 import sys from PyQt5.QtGui import QGuiApplication, QClipboard if __name__ == '__main__': app = QGuiApplication(sys.argv) clipboard = QGuiApplication.clipboard() def dataChanged(): copiedText = clipboard.text(QClipboard.Clipboard) if copiedText: print("copiedText:" + copiedText) sys.stdout.flush() def selectionChanged(): selectedText = clipboard.text(QClipboard.Selection) if selectedText: print("selectedText:" + selectedText) sys.stdout.flush() clipboard.dataChanged.connect(dataChanged) clipboard.selectionChanged.connect(selectionChanged) sys.exit(app.exec_())
def load_background_pixmap(self): # 截下当前屏幕的图像 self.load_pixmap = QGuiApplication.primaryScreen().grabWindow( QApplication.desktop().winId()) self.screen_width = self.load_pixmap.width() self.screen_height = self.load_pixmap.height()
@pyqtSlot() def abr(self): """Setup a random puzzle with a minimum number of assigned squares.""" self.disc.emit('succ') @pyqtSlot(str, str) def connect(self, login, password): self.mus.connect(login, password) i = 2 def stop(self): self.mus.stop_worker() if __name__ == "__main__": app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() ctx = engine.rootContext() guiController = GuiController() ctx.setContextProperty('guiController', guiController) ctx.setContextProperty("RemoteMusicPlayerGUI", engine) qml = r'D:/work/RemoteMusicPlayer/Gui/main.qml' a = engine.load(qml) app.exec_() guiController.stop() sys.exit()
def copy_roi_to_clipboard(self): pos, size = self.image_view.get_roi() QGuiApplication.clipboard().setText( f"{pos.x}, {pos.y}, {pos.x + size.x}, {pos.y + size.y}")
import os from PyQt5.QtCore import QUrl, Qt, QTimer, QMetaObject, QObject from PyQt5.QtGui import QGuiApplication from PyQt5.QtQml import QQmlApplicationEngine from dataProc import GraphRefresh from tools import Tools if __name__ == '__main__': try: pid = str(os.getpid()) PIDFILE = '/tmp/ui_process.pid' pidfile = open(PIDFILE,'w') pidfile.write(pid) pidfile.close() cwd = sys.path[0] myApp = QGuiApplication(sys.argv) appLabel = QQmlApplicationEngine() appLabel.addImportPath(cwd) appLabel.addImportPath(cwd + '/qml') appLabel.load(cwd + '/splash.qml') root = appLabel.rootObjects() context = appLabel.rootContext() g = GraphRefresh("/dev/ttyUSB0", 115200, 1, root, context) tools = Tools(root, context, g) context.setContextProperty('pyRoot', tools) myApp.exec_() sys.exit() except Exception as e : print(e) ;
path = cwd + "/logs/" max_Files = 5 def sorted_ls(path): mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime return list(sorted(os.listdir(path), key=mtime)) del_list = sorted_ls(path)[0:(len(sorted_ls(path))-max_Files)] for dfile in del_list: os.remove(path + dfile) if __name__ == "__main__": import sys # Create an instance of the application app = QGuiApplication(sys.argv) # Set window icon app.setWindowIcon(QIcon("note.png")) # Create QML engine engine = QQmlApplicationEngine() # Create a textlogger object textlogger = Textlogger() # And register it in the context of QML engine.rootContext().setContextProperty("textlogger", textlogger) # Load the qml file into the engine engine.load("main.qml") engine.quit.connect(app.quit) sys.exit(app.exec_())
# -*- coding: utf-8 -*- ''' (4)Python调用QML函数 QML中创建一个函数, Python中创建一个rootObject对象,并连接这个函数, 例子中,每隔1s,指针会旋转45 deg;。 ''' from PyQt5.QtCore import QUrl, QTimer from PyQt5.QtGui import QGuiApplication from PyQt5.QtQuick import QQuickView if __name__ == '__main__': path = 'test4.qml' # 加载的QML文件 app = QGuiApplication([]) view = QQuickView() view.engine().quit.connect(app.quit) view.setSource(QUrl(path)) view.show() timer = QTimer() timer.start(2000) root = view.rootObject() timer.timeout.connect(root.updateRotater) # 调用QML函数 app.exec_()
def main(): """The main entry point when used as a regular app It assumes a session is selected. When not, a dummy session None is used. The status line will tell that a real session has to be created or selected from the menu. """ global app # needed for making reports... matplotlib.use('Agg') app_Path = Path(__file__).parent.absolute() / '..' be = app_Path / 'QtQuickBackend' sys.path.append(str(be)) from backend_qtquick5 import FigureCanvasQTAggToolbar, MatplotlibIconProvider gd.config = startup() # always start without secondary session gd.config['Session2'] = None gd.globals = readGlobals() # sys_argv = sys.argv # sys_argv += ['--style', 'material'] app = QGuiApplication(sys.argv) # app.aboutToQuit.connect(shutdown) locale.setlocale(locale.LC_NUMERIC, "C"); # needed for filedialog app.setOrganizationName(gd.orgname) app.setOrganizationDomain(gd.orgdomain) app.setApplicationName(gd.appname) qmlRegisterType(FigureCanvasQTAggToolbar, "Backend", 1, 0, "FigureToolbar") imgProvider = MatplotlibIconProvider() # setup rootcontext to communicate with QML engine = QQmlApplicationEngine() engine.addImageProvider("mplIcons", imgProvider) gd.context = engine.rootContext() # Setup pieces gd.data_model = DataSensorsModel() gd.context.setContextProperty("sensorModel", gd.data_model) gd.mainPieces = FormPieces(data=gd.data_model) gd.context.setContextProperty("draw_mpl", gd.mainPieces) # model to create pieces gd.data_model2 = DataPiecesModel() gd.context.setContextProperty("makePiecesModel", gd.data_model2) # View piece gd.data_model3 = DataSensorsModel() gd.context.setContextProperty("sensorModel3", gd.data_model3) # model for secondary session gd.data_model4 = DataSensorsModel() gd.context.setContextProperty("sensorModel4", gd.data_model4) gd.mainView = FormView(data=gd.data_model3, data2=gd.data_model4) gd.context.setContextProperty("piece_mpl", gd.mainView) gd.data_model5 = DataPiecesModel() gd.context.setContextProperty("viewPiecesModel", gd.data_model5) # Boat gd.boattablemodel = BoatTableModel() gd.context.setContextProperty("boatTableModel", gd.boattablemodel) gd.boatPlots = BoatForm() gd.context.setContextProperty("boat_mpl", gd.boatPlots) # Crew gd.crewPlots = CrewForm() gd.context.setContextProperty("crew_mpl", gd.crewPlots) # Create rower tables and plots for potentially eight rowers for i in range(8): gd.rowertablemodel[i] = RowerTableModel(i) gd.context.setContextProperty("rowerTableModel"+str(i), gd.rowertablemodel[i]) gd.rowerPlots[i] = RowerForm(i) gd.context.setContextProperty("rower_mpl"+str(i), gd.rowerPlots[i]) # print(f'main: create the models rower {i} {gd.rowerPlots[i].update_figure}') gd.stretcherPlots[i] = StretcherForm(i) gd.context.setContextProperty("stretcher_mpl"+str(i), gd.stretcherPlots[i]) # Session info gd.data_model6 = DataBoatsModel() gd.context.setContextProperty("sInfoModel", gd.data_model6) gd.data_model6.load_boatsInfo() engine.load(str(app_Path / 'App' / 'qml' / 'main.qml')) gd.win = engine.rootObjects()[0] # set figures functions gd.mainPieces.figure = gd.win.findChild(QObject, "pieces").getFigure() gd.mainView.figure = gd.win.findChild(QObject, "viewpiece").getFigure() gd.boatPlots.figure = gd.win.findChild(QObject, "viewboat").getFigure() gd.crewPlots.figure = gd.win.findChild(QObject, "viewcrew").getFigure() sys.exit(app.exec_())
def _screenScaleFactor(self): physical_dpi = QGuiApplication.primaryScreen().physicalDotsPerInch() # Typically 'normal' screens have a DPI around 96. Modern high DPI screens are up around 220. # We scale the low DPI screens with a traditional 1, and double the high DPI ones. return 1.0 if physical_dpi < 150 else 2.0