class PlotWebView(QWebView): def __init__(self, name): QWebView.__init__(self) self.setPage(PlotWebPage(name)) self.setRenderHint(QPainter.Antialiasing, True) self.setContextMenuPolicy(Qt.NoContextMenu) self.settings().setAttribute(QWebSettings.JavascriptEnabled, True) self.settings().setAttribute(QWebSettings.LocalContentCanAccessFileUrls, True) self.settings().setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True) self.settings().clearMemoryCaches() self.__inspector_window = None shortcut = QShortcut(self) shortcut.setKey(Qt.Key_F12) shortcut.activated.connect(self.toggleInspector) def toggleInspector(self): if self.__inspector_window is None: self.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) web_inspector = QWebInspector() web_inspector.setPage(self.page()) self.__inspector_window = QMainWindow(self) self.__inspector_window.setCentralWidget(web_inspector) self.__inspector_window.resize(900, 600) self.__inspector_window.setVisible(False) self.__inspector_window.setVisible(not self.__inspector_window.isVisible())
class QtPysideApp(QApplication): def __init__(self, renderer, scene, title): QApplication.__init__(self, sys.argv) self.window = QMainWindow() self.window.setWindowTitle(title) self.window.resize(800, 600) # Get OpenGL 4.1 context glformat = QGLFormat() glformat.setVersion(4, 1) glformat.setProfile(QGLFormat.CoreProfile) glformat.setDoubleBuffer(False) self.glwidget = MyGlWidget(renderer, glformat, self, scene) self.window.setCentralWidget(self.glwidget) self.window.show() def __enter__(self): "setup for RAII using 'with' keyword" return self def __exit__(self, type_arg, value, traceback): "cleanup for RAII using 'with' keyword" self.glwidget.disposeGL() def run_loop(self): retval = self.exec_() sys.exit(retval)
def run(self): app = QApplication(sys.argv) w = QMainWindow() w.resize(700, 700) w.move(400, 0) w.setWindowTitle('Simple') w.show() w.isDrawMode = self.isDrawMode w.fileMenu = w.menuBar().addMenu("&File") w.fileSaveMenuItem = SfAction("&Save", w, shortcut="CTRL+S", tip="Save current scenario") w.fileSaveMenuItem.triggered.connect(self.fileSave) w.fileMenu.addAction(w.fileSaveMenuItem) w.fileMenu.addAction(SfAction("&Quit", w, slot=self.fileQuit(), shortcut="ALT+F4", tip="Quit SimFrames")) w.toolbar = w.addToolBar("Activities Toolbar") w.toolbar.setObjectName("ActivitiesToolbar") playActionsGroup = QActionGroup(w) w.toolbar.addAction(SfAction("&Play", w, "play.png", self.play, "CTRL+P", "Start the project", True, actionGroup=playActionsGroup )) w.toolbar.addAction(SfAction("&Stop", w, "stop.png", self.stop, "CTRL+F", "Stop executing", True, actionGroup=playActionsGroup, checked=True )) w.toolbar.addAction(SfSeparator(w)) self.mouseModeGroup = QActionGroup(w) w.toolbar.addAction(SfAction("&Move", self.mouseModeGroup, "moveMode.png", shortcut="CTRL+M", tip="Turn on mode to move components around canvas", checkable=True, checked=True)) self.drawAction = SfAction("&Draw", self.mouseModeGroup, "connectMode.png", shortcut="CTRL+D", tip="Turn on mode to connect components in canvas", checkable=True) w.toolbar.addAction(self.drawAction) w.toolbar.addAction(SfSeparator(w)) w.accordion = SfAccordion() functions = SfAccordionSection("Functions") functions.addComponents([SfComponent("add.png",), SfComponent("minus.png"), SfComponent("multiplication.png")]) inputSection = SfAccordionSection("Input") inputSection.addComponents([SfComponent("scale.png", ), SfComponent("square.png"), SfComponent("constant.png" )]) outputSection = SfAccordionSection("Output") outputSection.addComponents([SfComponent("txt.png", ), SfComponent("graph.png", )]) w.accordion.addSections([functions, inputSection, outputSection]) scene = SfGraphicsScene(w) self.canvas = SfGraphicsView(scene) scene.sceneRectChanged.connect(self.canvas.updateSceneRect) centralWidget = QWidget() mainLayout = QBoxLayout(QBoxLayout.LeftToRight, centralWidget) mainLayout.addWidget(w.accordion) mainLayout.addWidget(self.canvas) centralWidget.setLayout(mainLayout) w.setCentralWidget(centralWidget) w.quitAction = SfAction("&Quit", w, slot=self.fileQuit(), shortcut="ALT+F4", tip="Quit SimFrames") app.exec_()
class QBrowserApp: def __init__(self, filename, width, height): self._listeners = [] self.app = QApplication(sys.argv) self.win = QMainWindow() self.win.resize(width, height) self.browser = QWebView(_win) filename = os.path.abspath(filename) self.browser.setUrl(QUrl(filename)) filename = filename.split("?")[0] path, path = os.path.split(filename) self.browser.setHtml(open(filename).read(), QUrl.fromLocalFile(filename)) self.win.setCentralWidget(self.browser) self.win.show() from __pyjamas__ import pygwt_processMetas, set_main_frame from __pyjamas__ import set_gtk_module set_main_frame(self) def current_web_frame(self): return self.browser.page().currentFrame() def getDomDocument(self): element = self.current_web_frame().documentElement() return _Document(element) def addEventListener(self, element, event, callback): listener = Listener(element, event, callback) l_id = "__pyjamas_listener_%s__" % abs(id(listener)) self.current_web_frame().addToJavaScriptWindowObject(l_id, listener) js = "this.%s=function(e) { window.%s.execute(e); }" % (event, l_id) element._element.evaluateJavaScript(js) self._listeners.append(listener) def _alert(self, txt): js = "window.alert('%s');" % (txt) doc = self.getDomDocument() doc._element.evaluateJavaScript(js) def _addWindowEventListener(self, event, callback): listener = Listener(self.current_web_frame(), event, callback) l_id = "__pyjamas_listener_%s__" % abs(id(listener)) self.current_web_frame().addToJavaScriptWindowObject(l_id, listener) js = "this.%s=function(e) { window.%s.execute(e); }" % (event, l_id) doc = self.getDomDocument() doc._element.evaluateJavaScript(js) self._listeners.append(listener) def getUri(self): return unicode(self.current_web_frame().baseUrl().toString())
class QBrowserApp: def __init__(self, filename, width, height): self._listeners = [] self.app = QApplication(sys.argv) self.win = QMainWindow() self.win.resize(width, height) self.browser = QWebView(_win) filename = os.path.abspath(filename) self.browser.setUrl(QUrl(filename)) filename = filename.split("?")[0] path, path = os.path.split(filename) self.browser.setHtml( open(filename).read(), QUrl.fromLocalFile(filename)) self.win.setCentralWidget(self.browser) self.win.show() from __pyjamas__ import pygwt_processMetas, set_main_frame from __pyjamas__ import set_gtk_module set_main_frame(self) def current_web_frame(self): return self.browser.page().currentFrame() def getDomDocument(self): element = self.current_web_frame().documentElement() return _Document(element) def addEventListener(self, element, event, callback): listener = Listener(element, event, callback) l_id = "__pyjamas_listener_%s__" % abs(id(listener)) self.current_web_frame().addToJavaScriptWindowObject(l_id, listener) js = "this.%s=function(e) { window.%s.execute(e); }" % (event, l_id) element._element.evaluateJavaScript(js) self._listeners.append(listener) def _alert(self, txt): js = "window.alert('%s');" % (txt) doc = self.getDomDocument() doc._element.evaluateJavaScript(js) def _addWindowEventListener(self, event, callback): listener = Listener(self.current_web_frame(), event, callback) l_id = "__pyjamas_listener_%s__" % abs(id(listener)) self.current_web_frame().addToJavaScriptWindowObject(l_id, listener) js = "this.%s=function(e) { window.%s.execute(e); }" % (event, l_id) doc = self.getDomDocument() doc._element.evaluateJavaScript(js) self._listeners.append(listener) def getUri(self): return unicode(self.current_web_frame().baseUrl().toString())
def test(): from PyQt4.QtGui import QMainWindow from SMlib.utils.qthelpers import qapplication app = qapplication() win = QMainWindow() win.setWindowTitle("Status widgets test") win.resize(900, 300) statusbar = win.statusBar() swidgets = [] for klass in (ReadWriteStatus, EOLStatus, EncodingStatus, CursorPositionStatus, MemoryStatus, CPUStatus): swidget = klass(win, statusbar) swidgets.append(swidget) win.show() app.exec_()
def test(): from PyQt4.QtGui import QApplication, QMainWindow app = QApplication([]) w = QMainWindow() cf = CoverFlow() cf.resize(int(available_width() / 1.5), available_height() - 60) w.resize(cf.size() + QSize(30, 20)) model = DummyImageList() cf.setImages(model) cf.setCurrentSlide(39000) w.setCentralWidget(cf) w.show() cf.setFocus(Qt.OtherFocusReason) sys.exit(app.exec_())
def test(): from PyQt4.QtGui import QApplication, QMainWindow app = QApplication([]) w = QMainWindow() cf = CoverFlow() cf.resize(int(available_width()/1.5), available_height()-60) w.resize(cf.size()+QSize(30, 20)) model = DummyImageList() cf.setImages(model) cf.setCurrentSlide(39000) w.setCentralWidget(cf) w.show() cf.setFocus(Qt.OtherFocusReason) sys.exit(app.exec_())
def setup_win(self, layout): win = QMainWindow() self.__window = win win.setLayout(layout) win.resize(250, 150) win.move(300, 300) win.setWindowTitle(Application.title) win.statusBar().showMessage("Ready") win.show() widget = QWidget() self.__parent_widget = widget widget.setLayout(layout) win.setCentralWidget(widget)
class ZoomableWidgetTestCase(unittest.TestCase): def testExample(self): logging.debug(self.__class__.__name__ + ': testExample()') self.app = QApplication(sys.argv) self.window = QMainWindow() self.window.setWindowTitle("test ZoomableWidget") self.window.resize(300,300) self.app.setActiveWindow(self.window) self.window.show() self.scrollArea = ZoomableScrollArea(self.window) self.window.setCentralWidget(self.scrollArea) self.zoomableWidget = ZoomableWidget() self.scrollArea.setWidget(self.zoomableWidget) self.widget=VispaWidget(self.zoomableWidget) self.widget.move(10,10) self.widget.show() if not hasattr(unittest,"NO_GUI_TEST"): self.app.exec_()
class ZoomableWidgetTestCase(unittest.TestCase): def testExample(self): logging.debug(self.__class__.__name__ + ': testExample()') self.app = QApplication(sys.argv) self.window = QMainWindow() self.window.setWindowTitle("test ZoomableWidget") self.window.resize(300, 300) self.app.setActiveWindow(self.window) self.window.show() self.scrollArea = ZoomableScrollArea(self.window) self.window.setCentralWidget(self.scrollArea) self.zoomableWidget = ZoomableWidget() self.scrollArea.setWidget(self.zoomableWidget) self.widget = VispaWidget(self.zoomableWidget) self.widget.move(10, 10) self.widget.show() if not hasattr(unittest, "NO_GUI_TEST"): self.app.exec_()
class BoxDecayViewTestCase(unittest.TestCase): def testExample(self): logging.debug(self.__class__.__name__ + ': testExample()') self.app = QApplication(sys.argv) self.window = QMainWindow() self.window.setWindowTitle("test BoxDecayView") self.window.resize(300, 300) self.app.setActiveWindow(self.window) self.window.show() self.scrollArea = ZoomableScrollArea(self.window) self.window.setCentralWidget(self.scrollArea) self.boxDecayView = BoxDecayView() self.scrollArea.setWidget(self.boxDecayView) accessor = TestDataAccessor() self.boxDecayView.setDataAccessor(accessor) self.boxDecayView.setDataObjects(accessor.topLevelObjects()) self.boxDecayView.setBoxContentScript("str(object.Label)") self.boxDecayView.updateContent() for w in self.boxDecayView.children(): if hasattr(w, "setDragable"): w.setDragable(True, True) if not hasattr(unittest, "NO_GUI_TEST"): self.app.exec_()
class BoxDecayViewTestCase(unittest.TestCase): def testExample(self): logging.debug(self.__class__.__name__ + ': testExample()') self.app = QApplication(sys.argv) self.window = QMainWindow() self.window.setWindowTitle("test BoxDecayView") self.window.resize(300,300) self.app.setActiveWindow(self.window) self.window.show() self.scrollArea = ZoomableScrollArea(self.window) self.window.setCentralWidget(self.scrollArea) self.boxDecayView = BoxDecayView() self.scrollArea.setWidget(self.boxDecayView) accessor=TestDataAccessor() self.boxDecayView.setDataAccessor(accessor) self.boxDecayView.setDataObjects(accessor.topLevelObjects()) self.boxDecayView.setBoxContentScript("str(object.Label)") self.boxDecayView.updateContent() for w in self.boxDecayView.children(): if hasattr(w, "setDragable"): w.setDragable(True, True) if not hasattr(unittest,"NO_GUI_TEST"): self.app.exec_()
def prepare_application(cls, beforeCreate, factory): from PyQt4.QtGui import QApplication, QMainWindow from lunchinator import get_settings from lunchinator.log import initializeLogger from lunchinator.log.lunch_logger import setGlobalLoggingLevel from lunchinator.utilities import setValidQtParent initializeLogger() get_settings().set_verbose(True) setGlobalLoggingLevel(logging.DEBUG) app = QApplication(sys.argv) beforeCreate() window = QMainWindow() setValidQtParent(window) window.setWindowTitle("Layout Example") window.resize(300, 300) window.setCentralWidget(factory(window)) window.showNormal() window.raise_() window.activateWindow() return window, app
class LineDecayViewTestCase(unittest.TestCase): def testExample(self): logging.debug(self.__class__.__name__ + ': testExample()') try: from pxl.algorithms import AutoLayout except Exception: logging.info("LineDecayView needs PXL: " + exception_traceback()) return self.app = QApplication(sys.argv) self.window = QMainWindow() self.window.setWindowTitle("test LineDecayView") self.window.resize(300, 300) self.app.setActiveWindow(self.window) self.window.show() self.scrollArea = ZoomableScrollArea(self.window) self.window.setCentralWidget(self.scrollArea) self.lineDecayView = LineDecayView() self.scrollArea.setWidget(self.lineDecayView) accessor = TestDataAccessor() self.lineDecayView.setDataAccessor(accessor) self.lineDecayView.setDataObjects(accessor.topLevelObjects()) self.lineDecayView.updateContent() if not hasattr(unittest, "NO_GUI_TEST"): self.app.exec_()
class LineDecayViewTestCase(unittest.TestCase): def testExample(self): logging.debug(self.__class__.__name__ + ': testExample()') try: from pxl.algorithms import AutoLayout except Exception: logging.info("LineDecayView needs PXL: " + exception_traceback()) return self.app = QApplication(sys.argv) self.window = QMainWindow() self.window.setWindowTitle("test LineDecayView") self.window.resize(300,300) self.app.setActiveWindow(self.window) self.window.show() self.scrollArea = ZoomableScrollArea(self.window) self.window.setCentralWidget(self.scrollArea) self.lineDecayView = LineDecayView() self.scrollArea.setWidget(self.lineDecayView) accessor=TestDataAccessor() self.lineDecayView.setDataAccessor(accessor) self.lineDecayView.setDataObjects(accessor.topLevelObjects()) self.lineDecayView.updateContent() if not hasattr(unittest,"NO_GUI_TEST"): self.app.exec_()
class _WebkitRendererHelper(QObject): """This helper class is doing the real work. It is required to allow WebkitRenderer.render() to be called "asynchronously" (but always from Qt's GUI thread). """ def __init__(self, parent): """Copies the properties from the parent (WebkitRenderer) object, creates the required instances of QWebPage, QWebView and QMainWindow and registers some Slots. """ QObject.__init__(self) # Copy properties from parent for key, value in parent.__dict__.items(): setattr(self, key, value) # Create and connect required PyQt4 objects self._page = QWebPage() self._view = QWebView() self._view.setPage(self._page) self._window = QMainWindow() self._window.setCentralWidget(self._view) # Import QWebSettings for key, value in self.qWebSettings.iteritems(): self._page.settings().setAttribute(key, value) # Connect required event listeners self.connect( self._page, SIGNAL("loadFinished(bool)"), self._on_load_finished ) self.connect( self._page, SIGNAL("loadStarted()"), self._on_load_started ) self.connect( self._page.networkAccessManager(), SIGNAL("sslErrors(QNetworkReply *,const QList<QSslError>&)"), self._on_ssl_errors ) self.connect( self._page.networkAccessManager(), SIGNAL("finished(QNetworkReply *)"), self._on_each_reply ) # The way we will use this, it seems to be unesseccary to have # Scrollbars enabled. self._page.mainFrame().setScrollBarPolicy( Qt.Horizontal, Qt.ScrollBarAlwaysOff ) self._page.mainFrame().setScrollBarPolicy( Qt.Vertical, Qt.ScrollBarAlwaysOff ) self._page.settings().setUserStyleSheetUrl( QUrl("data:text/css,html,body{overflow-y:hidden !important;}") ) # Show this widget self._window.show() def __del__(self): """Clean up Qt4 objects. """ self._window.close() del self._window del self._view del self._page def render(self, url): """The real worker. Loads the page (_load_page) and awaits the end of the given 'delay'. While it is waiting outstanding QApplication events are processed. After the given delay, the Window or Widget (depends on the value of 'grabWholeWindow' is drawn into a QPixmap and postprocessed (_post_process_image). """ self._load_page(url, self.width, self.height, self.timeout) # Wait for end of timer. In this time, process # other outstanding Qt events. if self.wait > 0: if self.logger: self.logger.debug("Waiting %d seconds " % self.wait) waitToTime = time.time() + self.wait while time.time() < waitToTime and QApplication.hasPendingEvents(): QApplication.processEvents() if self.renderTransparentBackground: # Another possible drawing solution image = QImage(self._page.viewportSize(), QImage.Format_ARGB32) image.fill(QColor(255, 0, 0, 0).rgba()) # http://ariya.blogspot.com/2009/04/transparent-qwebview-and-qwebpage.html palette = self._view.palette() palette.setBrush(QPalette.Base, Qt.transparent) self._page.setPalette(palette) self._view.setAttribute(Qt.WA_OpaquePaintEvent, False) painter = QPainter(image) painter.setBackgroundMode(Qt.TransparentMode) self._page.mainFrame().render(painter) painter.end() else: if self.grabWholeWindow: # Note that this does not fully ensure that the # window still has the focus when the screen is # grabbed. This might result in a race condition. self._view.activateWindow() image = QPixmap.grabWindow(self._window.winId()) else: image = QPixmap.grabWidget(self._window) return self._post_process_image(image) def _load_page(self, url, width, height, timeout): """ This method implements the logic for retrieving and displaying the requested page. """ # This is an event-based application. So we have to wait until # "loadFinished(bool)" raised. cancelAt = time.time() + timeout self.__loading = True self.__loadingResult = False # Default # TODO: fromEncoded() needs to be used in some situations. Some # sort of flag should be passed in to WebkitRenderer maybe? #self._page.mainFrame().load(QUrl.fromEncoded(url)) self._page.mainFrame().load(QUrl(url)) while self.__loading: if timeout > 0 and time.time() >= cancelAt: raise RuntimeError("Request timed out on %s" % url) while QApplication.hasPendingEvents() and self.__loading: QCoreApplication.processEvents() if self.logger: self.logger.debug("Processing result") if not self.__loading_result: if self.logger: self.logger.warning("Failed to load %s" % url) raise BadURLException("Failed to load %s" % url) # Set initial viewport (the size of the "window") size = self._page.mainFrame().contentsSize() if self.logger: self.logger.debug("contentsSize: %s", size) if width > 0: size.setWidth(width) if height > 0: size.setHeight(height) self._window.resize(size) def _post_process_image(self, qImage): """If 'scaleToWidth' or 'scaleToHeight' are set to a value greater than zero this method will scale the image using the method defined in 'scaleRatio'. """ if self.scaleToWidth > 0 or self.scaleToHeight > 0: # Scale this image if self.scaleRatio == 'keep': ratio = Qt.KeepAspectRatio elif self.scaleRatio in ['expand', 'crop']: ratio = Qt.KeepAspectRatioByExpanding else: # 'ignore' ratio = Qt.IgnoreAspectRatio qImage = qImage.scaled( self.scaleToWidth, self.scaleToHeight, ratio ) if self.scaleRatio == 'crop': qImage = qImage.copy( 0, 0, self.scaleToWidth, self.scaleToHeight ) return qImage def _on_each_reply(self, reply): """Logs each requested uri""" self.logger.debug("Received %s" % (reply.url().toString())) # Eventhandler for "loadStarted()" signal def _on_load_started(self): """Slot that sets the '__loading' property to true.""" if self.logger: self.logger.debug("loading started") self.__loading = True # Eventhandler for "loadFinished(bool)" signal def _on_load_finished(self, result): """Slot that sets the '__loading' property to false and stores the result code in '__loading_result'. """ if self.logger: self.logger.debug("loading finished with result %s", result) self.__loading = False self.__loading_result = result # Eventhandler for "sslErrors(QNetworkReply *,const QList<QSslError>&)" # signal. def _on_ssl_errors(self, reply, errors): """Slot that writes SSL warnings into the log but ignores them.""" for e in errors: if self.logger: self.logger.warn("SSL: " + e.errorString()) reply.ignoreSslErrors()
chartView.chart().setAnimationOptions(options) alignment = self.m_legendComboBox.itemData( self.m_legendComboBox.currentIndex()) for chartView in self.m_charts: legend = chartView.chart().legend() if alignment == 0: legend.hide() else: legend.setAlignment(Qt.Alignment(alignment)) legend.show() if __name__ == '__main__': import sys from PyQt4.QtGui import QApplication, QMainWindow app = QApplication(sys.argv) window = QMainWindow() widget = ThemeWidget() window.setCentralWidget(widget) window.resize(900, 600) window.show() sys.exit(app.exec_())
import signal import sys #from PyMata.pymata import PyMata from PyQt4.QtGui import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QTextEdit app = QApplication([]) button_convert = QPushButton("Convert order") mainwindow = QMainWindow() mainwindow.resize(230, 400) mainwindow.setWindowTitle("Puuri abi") vbox = QVBoxLayout() vbox.addStretch(1) textedit = QTextEdit("First part") textedit2 = QTextEdit("Second part") textedit3 = QTextEdit(" ") vbox.addWidget(textedit) vbox.addWidget(textedit2) vbox.addWidget(textedit3) vbox.addWidget(button_convert) container = QWidget() container.setLayout(vbox) mainwindow.setCentralWidget(container) mainwindow.show() def convert_handler(): value = textedit2.toPlainText() #print(value)
def isCollapsed(self): return self.mainWidget.isCollapsed() def toggleCollapsed(self): self.setCollapsed(not self.isCollapsed()) if __name__ == "__main__": import sys from PyQt4.QtGui import QTextEdit app = QApplication(sys.argv) app.setStyle("qtcurve") win = QMainWindow() dock1 = DockWidget("1st dockwidget", win) dock1.setFeatures(dock1.features() | QDockWidget.DockWidgetVerticalTitleBar) combo = QComboBox(dock1) dock1.setWidget(combo) win.addDockWidget(Qt.LeftDockWidgetArea, dock1) dock2 = DockWidget("2nd dockwidget") dock2.setFeatures(dock1.features() | QDockWidget.DockWidgetVerticalTitleBar) button = QPushButton("Hello, world!", dock2) dock2.setWidget(button) win.addDockWidget(Qt.RightDockWidgetArea, dock2) edit = QTextEdit(win) win.setCentralWidget(edit) win.resize(640, 480) win.show() app.exec_()
cf.resize(int(available_width()/1.5), available_height()-60) w.resize(cf.size()+QSize(30, 20)) model = DummyImageList() cf.setImages(model) cf.setCurrentSlide(39000) w.setCentralWidget(cf) w.show() cf.setFocus(Qt.OtherFocusReason) sys.exit(app.exec_()) def main(args=sys.argv): return 0 if __name__ == '__main__': from PyQt4.QtGui import QApplication, QMainWindow app = QApplication([]) w = QMainWindow() cf = CoverFlow() cf.resize(int(available_width()/1.5), available_height()-60) w.resize(cf.size()+QSize(30, 20)) path = sys.argv[1] model = FileSystemImages(sys.argv[1]) cf.currentChanged[int].connect(model.currentChanged) cf.setImages(model) w.setCentralWidget(cf) w.show() cf.setFocus(Qt.OtherFocusReason) sys.exit(app.exec_())
def punchcard(ui, repo, *pats, **opts): """Generate a "punch card" graph of commit times. For drawing the graph, either PyQt4 or matplotlib can be used. The default is PyQt4, unless the --mpl option is given. Normally, all commits are registered in local time, so that commits at 10 AM local time in Europe and the USA show up on the same punch card entry. If --utc is given, all commit times are converted to UTC before registered. """ if pats: raise util.Abort('no argument allowed') filename = opts['filename'] if opts['datemin']: datemin = datetime.strptime(opts['datemin'], '%Y-%m-%d') else: datemin = None if opts['datemax']: datemax = datetime.strptime(opts['datemax'], '%Y-%m-%d') else: datemax = None users_include = set(opts['user']) users_exclude = set(opts['notuser']) user_filter = bool(users_include or users_exclude) title = opts.get('title') font = opts.get('font') or 'Arial' utc = opts.get('utc') data = [[0] * 24 for i in range(7)] cl = repo.changelog n = 0 ui.status('filtering changesets\n') for i in xrange(len(cl)): node = cl.read(cl.node(i)) # node[2] is a tuple of the date in UTC and the timezone offset. # If --utc is given, the offset can be ignored; otherwise if utc: date = datetime.utcfromtimestamp(node[2][0]) else: date = datetime.utcfromtimestamp(node[2][0] - node[2][1]) if (datemin and date < datemin) or (datemax and date > datemax): continue if user_filter: user = node[1] if users_include and user not in users_include: continue if user in users_exclude: continue day = (int(date.strftime('%w')) - 1) % 7 data[day][date.hour] += 1 n += 1 if n == 0: raise util.Abort('no matching changesets found') else: ui.status('punched %d changesets\n' % n) maxvalue = max(max(i) for i in data) or 1 xs, ys, rs, ss = [], [], [], [] for y, d in enumerate(data): for x, n in enumerate(d): xs.append(x) ys.append(y) rs.append(13. * n / maxvalue) ss.append(4. * n**2 / maxvalue) try: if opts.get('mpl') or opts.get('svg'): raise ImportError from PyQt4.QtCore import Qt, QPointF, QRectF from PyQt4.QtGui import QApplication, QColor, QFont, QImage, QLabel, \ QMainWindow, QPainter, QPixmap except ImportError: try: if opts.get('svg'): raise ImportError from matplotlib import pyplot except ImportError: if not opts.get('svg'): ui.status('Writing as SVG since neither PyQt4 nor ' 'matplotlib is available\n') if filename.endswith('.png'): filename = filename[:-4] + '.svg' f = open(filename, 'w') f.write('<?xml version="1.0" standalone="no"?>\n') f.write('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ' '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n') o = title and 30 or 0 # y coordinate offset f.write('<svg width="800" height="{0}" version="1.1" ' 'xmlns="http://www.w3.org/2000/svg">\n'.format(300 + o)) f.write('<style type="text/css"> circle {{fill: black;}} ' 'text {{font-family:{0};font-size:12;}} ' '.label{{font-size:12px;}}</style>\n'.format(font)) f.write('<rect x="0" y="0" width="800" height="{0}" ' 'style="fill:#efefef;"/>\n'.format(300 + o)) f.write('<line x1="35.5" y1="{0}" x2="{1}" y2="{0}" ' 'style="stroke:black;stroke-width:2"/>\n'.format( 264.5 + o, 45.5 + 24 * 31)) f.write('<line x1="35.5" y1="{0}" x2="35.5" y2="{1}" ' 'style="stroke:black;stroke-width:2"/>\n'.format( 14.5 + o, 264.5 + o)) for i, text in enumerate(days): f.write( '<text class="label" x="7.5" y="{0}">{1}</text>\n'.format( 34.5 + i * 34 + o, text)) for i in range(24): f.write('<text class="label" x="{0}" y="{1}">{2:02}</text>\n'. format(53.5 + i * 31, 280.5 + o, i)) for x, y, r in zip(xs, ys, rs): f.write('<circle cx="{0}" cy="{1}" r="{2}" fill="black"/>\n'. format(58.5 + x * 31, 30.5 + y * 34 + o, r)) if title: f.write('<text x="400" y="20" style="text-anchor:middle;">' '{0}</text>\n'.format(title)) f.write('</svg>') f.close() ui.status('created punch card in %s\n' % filename) else: pyplot.rc('font', family=font) # create a figure an axes with the same background color fig = pyplot.figure(figsize=(8, title and 3 or 2.5), facecolor='#efefef') ax = fig.add_subplot('111', axisbg='#efefef') # make the figure margins smaller if title: fig.subplots_adjust(left=0.06, bottom=0.04, right=0.98, top=0.95) ax.set_title(title, y=0.96).set_color('#333333') else: fig.subplots_adjust(left=0.06, bottom=0.08, right=0.98, top=0.99) # don't display the axes frame ax.set_frame_on(False) # plot the punch card data ax.scatter(xs, ys[::-1], s=ss, c='#333333', edgecolor='#333333') # hide the tick lines for line in ax.get_xticklines() + ax.get_yticklines(): line.set_alpha(0.0) # draw x and y lines (instead of axes frame) dist = -0.8 ax.plot([dist, 23.5], [dist, dist], c='#555555') ax.plot([dist, dist], [dist, 6.4], c='#555555') # select new axis limits ax.set_xlim(-1, 24) ax.set_ylim(-0.9, 6.9) # set tick labels and draw them smaller than normal ax.set_yticks(range(7)) for tx in ax.set_yticklabels(days[::-1]): tx.set_color('#555555') tx.set_size('x-small') ax.set_xticks(range(24)) for tx in ax.set_xticklabels(['%02d' % x for x in range(24)]): tx.set_color('#555555') tx.set_size('x-small') # get equal spacing for days and hours ax.set_aspect('equal') fig.savefig(filename) ui.status('created punch card in %s\n' % filename) if opts.get('display'): pyplot.show() else: app = QApplication([]) o = title and 30 or 0 # y coordinate offset image = QImage(800, 300 + o, QImage.Format_RGB32) painter = QPainter(image) painter.setRenderHints(QPainter.Antialiasing) painter.fillRect(0, 0, 800, 300 + o, QColor('#efefef')) painter.setPen(QColor('#555555')) painter.drawLine(QPointF(35.5, 264.5 + o), QPointF(45.5 + 24 * 31, 264.5 + o)) painter.drawLine(QPointF(35.5, 14.5 + o), QPointF(35.5, 264.5 + o)) painter.setFont(QFont(font, 8)) for i, text in enumerate(days): painter.drawText(QPointF(7.5, 34.5 + i * 34 + o), text) for i in range(24): text = '%02d' % i painter.drawText(QPointF(53.5 + i * 31, 280.5 + o), text) painter.setBrush(QColor('#333333')) painter.setPen(QColor('#333333')) for x, y, r in zip(xs, ys, rs): painter.drawEllipse(QPointF(58.5 + x * 31, 30.5 + y * 34 + o), r, r) if title: painter.setFont(QFont(font, 12)) painter.drawText(QRectF(0, 15, 800, 20), Qt.AlignCenter, title) painter.end() image.save(filename) ui.status('created punch card in %s\n' % filename) if opts.get('display'): win = QMainWindow() win.setWindowTitle('punchcard display') win.resize(800, 300 + o) lbl = QLabel(win) lbl.resize(800, 300 + o) lbl.setPixmap(QPixmap.fromImage(image)) win.show() app.exec_()
class UiController: def __init__(self, controller, debug_mode, logger): self.controller = controller self.datahandler = controller.datahandler self.debug_mode = debug_mode self.logger = logger ### Main Window self.main_widget = QMainWindow() self.main_widget.setAttribute(Qt.WA_Maemo5StackedWindow) self.main_ui = Ui_DropN900Widget() self.main_ui.setupUi(self.main_widget) # Stacked layout for context switching self.stacked_layout = QtGui.QStackedLayout() self.main_ui.centralwidget.setLayout(self.stacked_layout) # Menu items self.action_transfers = QtGui.QAction("Transfers", self.main_widget) self.action_settings = QtGui.QAction("Settings", self.main_widget) self.action_sync = QtGui.QAction("Synchronize", self.main_widget) self.action_sync_photos = QtGui.QAction("Sync Media", self.main_widget) self.action_console = QtGui.QAction("Show Log", self.main_widget) self.action_about = QtGui.QAction("About", self.main_widget) self.action_exit = QtGui.QAction("Exit", self.main_widget) self.main_ui.menubar.addAction(self.action_transfers) self.main_ui.menubar.addAction(self.action_settings) self.main_ui.menubar.addAction(self.action_sync) self.main_ui.menubar.addAction(self.action_sync_photos) self.main_ui.menubar.addAction(self.action_console) self.main_ui.menubar.addAction(self.action_about) self.main_ui.menubar.addAction(self.action_exit) # Connects self.action_transfers.triggered.connect(self.show_transfer_widget) self.action_sync.triggered.connect(self.synchronize_now) self.action_sync_photos.triggered.connect(self.synchronize_now_photos) self.action_settings.triggered.connect(self.show_settings_widget) self.action_console.triggered.connect(self.show_console) self.action_about.triggered.connect(self.show_about) self.action_exit.triggered.connect(self.shut_down) ### Trusted Login Widget self.trusted_login_widget = QWidget() self.trusted_login_ui = Ui_TrustedLoginWidget() self.trusted_login_ui.setupUi(self.trusted_login_widget) self.trusted_login_ui.label_icon.setPixmap(QPixmap(self.datahandler.datapath("ui/images/dropn900_logo.png")).scaled(65,65)) # Connects self.trusted_login_ui.button_auth.clicked.connect(self.try_trusted_login) ### Manager Widget self.manager_widget = QWidget() self.manager_ui = Ui_ManagerWidget() self.manager_ui.setupUi(self.manager_widget) # Tree Controller tree = self.manager_ui.tree_widget self.tree_controller = TreeController(tree, self.manager_ui, self.controller, self.logger) # Hide public link elements on start self.manager_ui.button_copy_public_link.hide() self.manager_ui.button_open_public_link.hide() # Connects self.manager_ui.button_copy_public_link.clicked.connect(self.copy_item_link) self.manager_ui.button_open_public_link.clicked.connect(self.open_item_link) self.manager_ui.button_download.clicked.connect(self.item_download) self.manager_ui.button_upload.clicked.connect(self.item_upload) self.manager_ui.button_rename.clicked.connect(self.item_rename) self.manager_ui.button_remove.clicked.connect(self.item_remove) self.manager_ui.button_new_folder.clicked.connect(self.item_new_folder) self.manager_ui.sync_button.clicked.connect(self.synchronize_now) self.last_dl_location = None self.last_ul_location = None ### Console widget self.console_widget = QWidget(self.main_widget, Qt.Window) self.console_widget.setAttribute(Qt.WA_Maemo5StackedWindow) self.console_ui = Ui_ConsoleWidget() self.console_ui.setupUi(self.console_widget) self.console_ui.button_save.clicked.connect(self.save_log_to_file) self.console_ui.button_back.clicked.connect(self.hide_console) ### Settings widget self.settings_widget = None ### Fill stacked layout self.stacked_layout.addWidget(self.trusted_login_widget) self.stacked_layout.addWidget(self.manager_widget) self.stacked_layout.setCurrentWidget(self.trusted_login_widget) ### Loading Widget self.loading_widget = QWidget(self.manager_widget) self.loading_ui = Ui_LoadingWidget() self.loading_ui.setupUi(self.loading_widget) self.manager_ui.action_layout.insertWidget(3, self.loading_widget) self.loading_widget.hide() self.tree_controller.set_loading_ui(self.loading_ui) # Init loading animation self.loading_animation = QMovie(self.datahandler.datapath("ui/images/loading.gif"), "GIF", self.loading_ui.load_animation_label) self.loading_animation.setCacheMode(QMovie.CacheAll) self.loading_animation.setSpeed(150) self.loading_animation.setScaledSize(QtCore.QSize(48,48)) self.loading_ui.load_animation_label.setMovie(self.loading_animation) # Init hide timer and icons for information messages self.information_message_timer = QTimer() self.information_message_timer.setSingleShot(True) self.information_message_timer.timeout.connect(self.hide_information_message) self.information_icon_ok = QPixmap(self.datahandler.datapath("ui/icons/check.png")).scaled(24,24) self.information_icon_error = QPixmap(self.datahandler.datapath("ui/icons/cancel.png")).scaled(24,24) self.information_icon_queue = QPixmap(self.datahandler.datapath("ui/icons/queue.png")).scaled(24,24) ### About dialog self.about_dialog = AboutDialog(self) self.set_synching(False) def set_synching(self, syncing): self.manager_ui.sync_button.setVisible(not syncing) self.manager_ui.sync_label.setVisible(syncing) def set_settings_widget(self, settings_widget): self.settings_widget = settings_widget def set_transfer_widget(self, transfer_widget): self.transfer_widget = transfer_widget def synchronize_now(self): self.settings_widget.sync_now_clicked() def synchronize_now_photos(self): self.controller.sync_manager.sync_media() def show(self): # Nokia N900 screen resolution, full screen self.main_widget.resize(800, 480) self.main_widget.show() self.main_widget.showMaximized() def show_settings_widget(self): if self.settings_widget != None: if not self.settings_widget.isVisible(): self.settings_widget.show() self.settings_widget.check_settings() def show_transfer_widget(self): if self.settings_widget.isVisible(): self.settings_widget.hide() self.transfer_widget.show() def show_about(self): if not self.about_dialog.isVisible(): self.about_dialog.show() def show_note(self, message): QMaemo5InformationBox.information(None, QString(message), 0) def show_banner(self, message, timeout = 5000): QMaemo5InformationBox.information(None, QString(message), timeout) def show_loading_ui(self, message = "", loading = True): self.loading_ui.info_label.setText(message) self.loading_ui.info_label_icon.hide() self.thumb_was_visible = self.manager_ui.thumb_container.isVisible() self.manager_ui.thumb_container.hide() self.loading_widget.show() self.loading_ui.load_animation_label.setVisible(loading) if loading: self.loading_animation.start() else: self.loading_animation.stop() def show_information_ui(self, message, succesfull, timeout = 4000): self.loading_ui.load_animation_label.hide() self.thumb_was_visible = self.manager_ui.thumb_container.isVisible() if self.thumb_was_visible: self.manager_ui.thumb_container.hide() self.loading_ui.info_label.setText(message) if succesfull == None: icon = self.information_icon_queue elif succesfull: icon = self.information_icon_ok else: icon = self.information_icon_error self.loading_ui.info_label_icon.setPixmap(icon) self.loading_ui.info_label_icon.show() self.loading_widget.show() self.information_message_timer.start(timeout) def hide_loading_ui(self): if not self.information_message_timer.isActive(): self.loading_widget.hide() if self.loading_animation.state() == QMovie.Running: self.loading_animation.stop() def hide_information_message(self): self.loading_ui.info_label_icon.hide() self.hide_loading_ui() self.manager_ui.thumb_container.setVisible(self.thumb_was_visible) def try_trusted_login(self): self.trusted_login_ui.label_error.setText("") email = self.trusted_login_ui.line_edit_email.text() password = self.trusted_login_ui.line_edit_password.text() error = None if email.isEmpty(): error = "Email can't be empty!" elif email.count("@") != 1: error = "Invalid email, check your @ signs!" elif email.contains(" "): error = "Invalid email, can't have spaces!" elif password.isEmpty(): error = "Password can't be empty!" if error == None: self.show_banner("Authenticating...", 3000) self.set_trusted_login_info("Authenticating, please wait...") self.truested_email = self.datahandler.to_unicode(str(email.toUtf8())) self.trusted_password = self.datahandler.to_unicode(str(password.toUtf8())) QTimer.singleShot(100, self.do_trusted_login_networking) else: self.set_trusted_login_error(error) def set_trusted_login_error(self, error): self.trusted_login_ui.label_error.setStyleSheet("color: #9d1414;") self.trusted_login_ui.label_error.setText(error) self.truested_email = None self.trusted_password = None def set_trusted_login_info(self, info): self.trusted_login_ui.label_error.setStyleSheet("color: #149d2b;") self.trusted_login_ui.label_error.setText(info) def do_trusted_login_networking(self): self.controller.end_trusted_auth(self.truested_email.encode("utf-8"), self.trusted_password.encode("utf-8")) self.truested_email = None self.trusted_password = None def reset_trusted_login(self): self.trusted_login_ui.line_edit_email.clear() self.trusted_login_ui.line_edit_password.clear() self.trusted_login_ui.label_error.clear() def switch_context(self, view = None): widget = None if view == "trustedlogin": widget = self.trusted_login_widget if view == "manager": widget = self.manager_widget if view == "console": self.console_widget.show() if view == None and self.last_view != None: widget = self.last_view if widget != None: self.last_view = self.stacked_layout.currentWidget() self.stacked_layout.setCurrentWidget(widget) def get_selected_data(self): return self.tree_controller.selected_data # Signal handlers def shut_down(self): self.main_widget.close() def show_console(self): if self.console_widget.isVisible() == False: self.switch_context("console") else: self.hide_console() def hide_console(self): self.console_widget.hide() def save_log_to_file(self): filename = self.datahandler.get_data_dir_path() + "dropn900.log" log_string = str(self.console_ui.text_area.toPlainText()) try: log_file = open(filename, "w") log_file.write(log_string) log_file.close() self.show_banner("Log saved to " + filename) except IOError: self.logger.error("Could not open " + filename + " to save log") def browser_control_clicked(self): if self.controller.connected: self.switch_context() else: self.controller.end_auth() def copy_item_link(self): url = self.tree_controller.current_public_link if url == None: return self.datahandler.copy_url_to_clipboard(url) def open_item_link(self): url = self.tree_controller.current_public_link if url == None: return QDesktopServices.openUrl(QtCore.QUrl(url)) def item_download(self): data = self.get_selected_data() if data == None: return if self.datahandler.dont_show_dl_dialog == False: # This dialog shows sometimes strange stuff on maemo5 # It's a PyQt4 bug and its the best we got, you can cope with this if self.last_dl_location == None: self.last_dl_location = self.datahandler.get_data_dir_path() local_folder_path = QFileDialog.getExistingDirectory(self.manager_widget, QString("Select Download Folder"), QString(self.last_dl_location), QFileDialog.ShowDirsOnly|QFileDialog.HideNameFilterDetails|QFileDialog.ReadOnly) if local_folder_path.isEmpty(): return py_unicode_path = self.datahandler.to_unicode(str(local_folder_path.toUtf8())) self.last_dl_location = py_unicode_path store_path = py_unicode_path + "/" + data.name else: dir_check = QDir(self.datahandler.get_data_dir_path()) if not dir_check.exists(): self.show_note("Cannot download, destination " + self.datahandler.get_data_dir_path() + " does not exist. Please set a new folder in settings.") return store_path = self.datahandler.get_data_dir_path() + data.name self.controller.connection.get_file(data.path, data.root, store_path, data.get_size(), data.mime_type) def item_upload(self): data = self.get_selected_data() if data == None or not data.is_folder(): return # This dialog shows sometimes strange stuff on maemo5 # It's a PyQt4 bug and its the best we got, you can cope with this if self.last_ul_location == None: self.last_ul_location = self.datahandler.get_data_dir_path() local_file_path = QFileDialog.getOpenFileName(self.manager_widget, QString("Select File for Upload"), QString(self.last_ul_location)) if local_file_path.isEmpty(): return py_unicode_path = self.datahandler.to_unicode(str(local_file_path.toUtf8())) self.last_ul_location = py_unicode_path[0:py_unicode_path.rfind("/")] self.controller.connection.upload_file(data.path, data.root, py_unicode_path) def item_rename(self): data = self.get_selected_data() if data == None: return # Get new name from user old_name = data.get_name() keyword = "file" if not data.is_folder() else "folder" new_name, ok = QInputDialog.getText(None, "Renaming " + keyword, "Give new name for " + keyword + " " + old_name, QtGui.QLineEdit.Normal, old_name) if not ok: return # Validate with QString if not self.is_name_valid(new_name, keyword): return # Make QString to python 'unicode' new_name = self.datahandler.to_unicode(str(new_name.toUtf8())) if old_name == new_name: return # Extension will be lost, ask user if he wants to leave it q_old_name = QtCore.QString(old_name) if q_old_name.contains("."): if not new_name.contains("."): format = old_name[q_old_name.lastIndexOf("."):] confirmation = QMessageBox.question(None, "Extension missing", "Do you want to append the original '" + format + "' extensions to the filename '" + new_name + "'?", QMessageBox.Yes, QMessageBox.No) if confirmation == QMessageBox.Yes: new_name.append(format) # Get final new path and rename if data.parent == "/": new_name = data.parent + new_name else: new_name = data.parent + "/" + new_name self.controller.connection.rename(data.root, data.path, new_name, data) def item_remove(self): data = self.get_selected_data() if data == None: return if data.is_folder(): confirmation = QMessageBox.question(None, "Remove folder verification", "Are you sure you want to remove the entire folder " + data.get_name() +"?", QMessageBox.Yes, QMessageBox.Cancel) else: confirmation = QMessageBox.question(None, "Remove file verification", "Are you sure you want to remove " + data.get_name() +"?", QMessageBox.Yes, QMessageBox.Cancel) if confirmation == QMessageBox.Yes: self.controller.connection.remove_file(data.root, data.path, data.parent, data.is_folder()) def item_new_folder(self): data = self.get_selected_data() if data == None: return if not data.is_folder(): return full_create_path = data.path + "/" new_folder_name, ok = QInputDialog.getText(None, "Give new folder name", "") if not ok: return # Validate QString if not self.is_name_valid(new_folder_name, "folder"): return # Make QString to python unicode new_folder_name = self.datahandler.to_unicode(str(new_folder_name.toUtf8())) full_create_path = data.path + "/" + new_folder_name self.controller.connection.create_folder(data.root, full_create_path, new_folder_name, data.path) def is_name_valid(self, name, item_type): if name.isEmpty() or name.isNull(): return False if name.contains("/"): self.show_information_ui("Cant use / in new " + item_type + " name", False) return False if name.contains("\\"): self.show_information_ui("Cant use \ in new " + item_type + " name", False) return False if name.startsWith(" "): self.show_information_ui("New " + item_type + " name cant start with a space", False) return False if name.endsWith(" "): self.show_information_ui("New " + item_type + " name cant end with a space", False) return False return True
def punchcard(ui, repo, *pats, **opts): """Generate a "punch card" graph of commit times. For drawing the graph, either PyQt4 or matplotlib can be used. The default is PyQt4, unless the --mpl option is given. Normally, all commits are registered in local time, so that commits at 10 AM local time in Europe and the USA show up on the same punch card entry. If --utc is given, all commit times are converted to UTC before registered. """ if pats: raise util.Abort('no argument allowed') filename = opts['filename'] if opts['datemin']: datemin = datetime.strptime(opts['datemin'], '%Y-%m-%d') else: datemin = None if opts['datemax']: datemax = datetime.strptime(opts['datemax'], '%Y-%m-%d') else: datemax = None users_include = set(opts['user']) users_exclude = set(opts['notuser']) user_filter = bool(users_include or users_exclude) title = opts.get('title') font = opts.get('font') or 'Arial' utc = opts.get('utc') data = [[0] * 24 for i in range(7)] cl = repo.changelog n = 0 ui.status('filtering changesets\n') for i in xrange(len(cl)): node = cl.read(cl.node(i)) # node[2] is a tuple of the date in UTC and the timezone offset. # If --utc is given, the offset can be ignored; otherwise if utc: date = datetime.utcfromtimestamp(node[2][0]) else: date = datetime.utcfromtimestamp(node[2][0] - node[2][1]) if (datemin and date < datemin) or (datemax and date > datemax): continue if user_filter: user = node[1] if users_include and user not in users_include: continue if user in users_exclude: continue day = (int(date.strftime('%w')) - 1) % 7 data[day][date.hour] += 1 n += 1 if n == 0: raise util.Abort('no matching changesets found') else: ui.status('punched %d changesets\n' % n) maxvalue = max(max(i) for i in data) or 1 xs, ys, rs, ss = [], [], [], [] for y, d in enumerate(data): for x, n in enumerate(d): xs.append(x); ys.append(y); rs.append(13.*n/maxvalue) ss.append(4.*n**2/maxvalue) try: if opts.get('mpl') or opts.get('svg'): raise ImportError from PyQt4.QtCore import Qt, QPointF, QRectF from PyQt4.QtGui import QApplication, QColor, QFont, QImage, QLabel, \ QMainWindow, QPainter, QPixmap except ImportError: try: if opts.get('svg'): raise ImportError from matplotlib import pyplot except ImportError: if not opts.get('svg'): ui.status('Writing as SVG since neither PyQt4 nor ' 'matplotlib is available\n') if filename.endswith('.png'): filename = filename[:-4] + '.svg' f = open(filename, 'w') f.write('<?xml version="1.0" standalone="no"?>\n') f.write('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ' '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n') o = title and 30 or 0 # y coordinate offset f.write('<svg width="800" height="{0}" version="1.1" ' 'xmlns="http://www.w3.org/2000/svg">\n'.format(300+o)) f.write('<style type="text/css"> circle {{fill: black;}} ' 'text {{font-family:{0};font-size:12;}} ' '.label{{font-size:12px;}}</style>\n'.format(font)) f.write('<rect x="0" y="0" width="800" height="{0}" ' 'style="fill:#efefef;"/>\n'.format(300+o)) f.write('<line x1="35.5" y1="{0}" x2="{1}" y2="{0}" ' 'style="stroke:black;stroke-width:2"/>\n' .format(264.5+o,45.5+24*31)) f.write('<line x1="35.5" y1="{0}" x2="35.5" y2="{1}" ' 'style="stroke:black;stroke-width:2"/>\n' .format(14.5+o,264.5+o)) for i, text in enumerate(days): f.write('<text class="label" x="7.5" y="{0}">{1}</text>\n' .format(34.5+i*34+o,text)) for i in range(24): f.write('<text class="label" x="{0}" y="{1}">{2:02}</text>\n' .format(53.5 + i*31, 280.5 + o, i)) for x, y, r in zip(xs, ys, rs): f.write('<circle cx="{0}" cy="{1}" r="{2}" fill="black"/>\n' .format(58.5 + x*31, 30.5 + y*34 + o, r)) if title: f.write('<text x="400" y="20" style="text-anchor:middle;">' '{0}</text>\n'.format(title)) f.write('</svg>') f.close() ui.status('created punch card in %s\n' % filename) else: pyplot.rc('font', family=font) # create a figure an axes with the same background color fig = pyplot.figure(figsize=(8, title and 3 or 2.5), facecolor='#efefef') ax = fig.add_subplot('111', axisbg='#efefef') # make the figure margins smaller if title: fig.subplots_adjust(left=0.06, bottom=0.04, right=0.98, top=0.95) ax.set_title(title, y=0.96).set_color('#333333') else: fig.subplots_adjust(left=0.06, bottom=0.08, right=0.98, top=0.99) # don't display the axes frame ax.set_frame_on(False) # plot the punch card data ax.scatter(xs, ys[::-1], s=ss, c='#333333', edgecolor='#333333') # hide the tick lines for line in ax.get_xticklines() + ax.get_yticklines(): line.set_alpha(0.0) # draw x and y lines (instead of axes frame) dist = -0.8 ax.plot([dist, 23.5], [dist, dist], c='#555555') ax.plot([dist, dist], [dist, 6.4], c='#555555') # select new axis limits ax.set_xlim(-1, 24) ax.set_ylim(-0.9, 6.9) # set tick labels and draw them smaller than normal ax.set_yticks(range(7)) for tx in ax.set_yticklabels(days[::-1]): tx.set_color('#555555') tx.set_size('x-small') ax.set_xticks(range(24)) for tx in ax.set_xticklabels(['%02d' % x for x in range(24)]): tx.set_color('#555555') tx.set_size('x-small') # get equal spacing for days and hours ax.set_aspect('equal') fig.savefig(filename) ui.status('created punch card in %s\n' % filename) if opts.get('display'): pyplot.show() else: app = QApplication([]) o = title and 30 or 0 # y coordinate offset image = QImage(800, 300 + o, QImage.Format_RGB32) painter = QPainter(image) painter.setRenderHints(QPainter.Antialiasing) painter.fillRect(0, 0, 800, 300 + o, QColor('#efefef')) painter.setPen(QColor('#555555')) painter.drawLine(QPointF(35.5, 264.5 + o), QPointF(45.5 + 24 * 31, 264.5 + o)) painter.drawLine(QPointF(35.5, 14.5 + o), QPointF(35.5, 264.5 + o)) painter.setFont(QFont(font, 8)) for i, text in enumerate(days): painter.drawText(QPointF(7.5, 34.5 + i * 34 + o), text) for i in range(24): text = '%02d' % i painter.drawText(QPointF(53.5 + i * 31, 280.5 + o), text) painter.setBrush(QColor('#333333')) painter.setPen(QColor('#333333')) for x, y, r in zip(xs, ys, rs): painter.drawEllipse(QPointF(58.5 + x * 31, 30.5 + y * 34 + o), r, r) if title: painter.setFont(QFont(font, 12)) painter.drawText(QRectF(0, 15, 800, 20), Qt.AlignCenter, title) painter.end() image.save(filename) ui.status('created punch card in %s\n' % filename) if opts.get('display'): win = QMainWindow() win.setWindowTitle('punchcard display') win.resize(800, 300 + o) lbl = QLabel(win) lbl.resize(800, 300 + o) lbl.setPixmap(QPixmap.fromImage(image)) win.show() app.exec_()
def main(): ns = _parseCommandLine() _fixSysPath(ns.binary) import qutepart # after correct sys.path has been set with open(ns.file) as file: text = unicode(file.read(), 'utf8') if ns.debug: logging.getLogger('qutepart').setLevel(logging.DEBUG) app = QApplication(sys.argv) window = QMainWindow() qpart = qutepart.Qutepart() window.setCentralWidget(qpart) firstLine = text.splitlines()[0] if text else None qpart.detectSyntax(sourceFilePath=ns.file, firstLine=firstLine) qpart.lineLengthEdge = 20 qpart.drawIncorrectIndentation = True qpart.drawAnyWhitespace = False qpart.indentUseTabs = False qpart.text = text qpart.setWindowTitle(ns.file) menu = { 'File': ('printAction', ), 'Bookmarks': ('toggleBookmarkAction', 'nextBookmarkAction', 'prevBookmarkAction'), 'Navigation': ( 'scrollUpAction', 'scrollDownAction', 'selectAndScrollUpAction', 'selectAndScrollDownAction', ), 'Indentation': ('increaseIndentAction', 'decreaseIndentAction', 'autoIndentLineAction', 'indentWithSpaceAction', 'unIndentWithSpaceAction'), 'Lines': ('moveLineUpAction', 'moveLineDownAction', 'deleteLineAction', 'copyLineAction', 'pasteLineAction', 'cutLineAction', 'duplicateLineAction'), 'Edit': ('invokeCompletionAction', 'undoAction', 'redoAction') } for k, v in menu.items(): menuObject = window.menuBar().addMenu(k) for actionName in v: menuObject.addAction(getattr(qpart, actionName)) qpart.userWarning.connect( lambda text: window.statusBar().showMessage(text, 3000)) window.resize(800, 600) window.show() from PyQt4.QtCore import QTimer if ns.quit: QTimer.singleShot(0, app.quit) return app.exec_()
class ConnectableWidgetTestCase(unittest.TestCase): def testExample(self): logging.debug(self.__class__.__name__ + ': testExample()') self.app = QApplication(sys.argv) self.window = QMainWindow() self.window.setWindowTitle("test ConnectableWidget") self.app.setActiveWindow(self.window) self.window.resize(800, 600) self.window.show() widgets = [] rowOneY = 10 widget = ConnectableWidget(self.window, "empty") widget.move(10, rowOneY) widgets.append(widget) widget = ConnectableWidget(self.window, "with ports") widget.move(210, rowOneY) widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) widget = ConnectableWidget(self.window, "with port names") widget.move(410, rowOneY) widget.setShowPortNames(True) widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) # ________________________________ autocale _______________________________ rowTwoY = 130 widget = ConnectableWidget(self.window, "autocale") widget.move(10, rowTwoY) widget.enableAutosizing(True, False) widgets.append(widget) widget = ConnectableWidget(self.window, "with ports") widget.move(210, rowTwoY) widget.enableAutosizing(True, False) widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) widget = ConnectableWidget(self.window, "with port names sdfsdfg dfgsdf") widget.move(410, rowTwoY) widget.enableAutosizing(True, False) widget.setShowPortNames(True) widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) # ________________________ special _____________________ rowThreeX = 230 widget = ConnectableWidget(self.window) widget.move(10, rowThreeX) widget.enableAutosizing(True, False) widgets.append(widget) widget = ConnectableWidget(self.window) widget.move(80, rowThreeX) widget.enableAutosizing(True, False) widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) widget = ConnectableWidget(self.window) widget.move(150, rowThreeX) widget.enableAutosizing(True, False) widget.setText("with text") widgets.append(widget) widget = ConnectableWidget(self.window) widget.move(220, rowThreeX) widget.enableAutosizing(True, False) widget.setTitle("with title") widget.setText("with text") widgets.append(widget) widget = ConnectableWidget(self.window, "many ports") widget.move(410, rowThreeX) widget.enableAutosizing(True, False) widget.setShowPortNames(True) widget.addSinkPort("first sink port") widget.addSinkPort("another sink port") widget.addSinkPort("another sink port") widget.addSinkPort("another sink port") widget.addSinkPort("another sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widgets.append(widget) # _________________________ ports and text __________________________ rowFourX = 300 widget = ConnectableWidget(self.window) widget.move(10, rowFourX) widget.enableAutosizing(True, False) widget.setTitle("with title") widget.setText("with text") widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) widget = ConnectableWidget(self.window) widget.move(120, rowFourX) widget.enableAutosizing(True, False) widget.setShowPortNames(True) widget.setTitle("with port names and text") widget.setText("with text") widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) # _________________________ test __________________________ rowFiveX = 370 for widget in widgets: widget.scheduleRearangeContent() widget.show() if not hasattr(unittest, "NO_GUI_TEST"): self.app.exec_()
class ConnectableWidgetTestCase(unittest.TestCase): def testExample(self): logging.debug(self.__class__.__name__ +': testExample()') self.app = QApplication(sys.argv) self.window = QMainWindow() self.window.setWindowTitle("test ConnectableWidget") self.app.setActiveWindow(self.window) self.window.resize(800, 600) self.window.show() widgets = [] rowOneY = 10 widget = ConnectableWidget(self.window, "empty") widget.move(10, rowOneY) widgets.append(widget) widget = ConnectableWidget(self.window, "with ports") widget.move(210, rowOneY) widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) widget = ConnectableWidget(self.window, "with port names") widget.move(410, rowOneY) widget.setShowPortNames(True) widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) # ________________________________ autocale _______________________________ rowTwoY = 130 widget = ConnectableWidget(self.window, "autocale") widget.move(10, rowTwoY) widget.enableAutosizing(True, False) widgets.append(widget) widget = ConnectableWidget(self.window, "with ports") widget.move(210, rowTwoY) widget.enableAutosizing(True, False) widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) widget = ConnectableWidget(self.window, "with port names sdfsdfg dfgsdf") widget.move(410, rowTwoY) widget.enableAutosizing(True, False) widget.setShowPortNames(True) widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) # ________________________ special _____________________ rowThreeX = 230 widget = ConnectableWidget(self.window) widget.move(10, rowThreeX) widget.enableAutosizing(True, False) widgets.append(widget) widget = ConnectableWidget(self.window) widget.move(80, rowThreeX) widget.enableAutosizing(True, False) widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) widget = ConnectableWidget(self.window) widget.move(150, rowThreeX) widget.enableAutosizing(True, False) widget.setText("with text") widgets.append(widget) widget = ConnectableWidget(self.window) widget.move(220, rowThreeX) widget.enableAutosizing(True, False) widget.setTitle("with title") widget.setText("with text") widgets.append(widget) widget = ConnectableWidget(self.window, "many ports") widget.move(410, rowThreeX) widget.enableAutosizing(True, False) widget.setShowPortNames(True) widget.addSinkPort("first sink port") widget.addSinkPort("another sink port") widget.addSinkPort("another sink port") widget.addSinkPort("another sink port") widget.addSinkPort("another sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widget.addSourcePort("another sourcePort") widgets.append(widget) # _________________________ ports and text __________________________ rowFourX = 300 widget = ConnectableWidget(self.window) widget.move(10, rowFourX) widget.enableAutosizing(True, False) widget.setTitle("with title") widget.setText("with text") widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) widget = ConnectableWidget(self.window) widget.move(120, rowFourX) widget.enableAutosizing(True, False) widget.setShowPortNames(True) widget.setTitle("with port names and text") widget.setText("with text") widget.addSinkPort("first sink port") widget.addSourcePort("first source port") widget.addSourcePort("second sourcePort") widgets.append(widget) # _________________________ test __________________________ rowFiveX = 370 for widget in widgets: widget.scheduleRearangeContent() widget.show() if not hasattr(unittest,"NO_GUI_TEST"): self.app.exec_()
return polylines if __name__ == '__main__': grid_path = None grid_data_path = None polyline_root_path = None if len(sys.argv) == 4: grid_path = sys.argv[1] grid_data_path = sys.argv[2] polyline_root_path = sys.argv[3] app = QApplication(["Slice Viewer"]) window = QMainWindow() window.resize(1024, 768) textures, bounds, nx, ny, nz, data_range , faults = createDataStructures(grid_path, grid_data_path , polyline_root_path) polylines = readPolylines(root_path=polyline_root_path) color_scales = createColorScales() textures["color_scale"] = color_scales[color_scales.keys()[0]] viewer = SliceViewer(textures=textures, volume_bounds=bounds, color_scales=color_scales, data_range=data_range, polylines=polylines , faults = faults) viewer.setSliceSize(width=nx, height=ny) slice_settings = SliceSettingsWidget(max_slice_count=nz, color_scales=color_scales.keys()) slice_settings.inactiveCellsHidden.connect(viewer.hideInactiveCells) slice_settings.currentSliceChanged.connect(viewer.setCurrentSlice)
def collapsed(self): return self.mainWidget.isCollapsed() collapsed = property(collapsed, setCollapsed) def toggleCollapsed(self): self.setCollapsed(self.collapsed) self.stateChanged.emit(self.collapsed) if __name__ == "__main__": import sys from PyQt4.QtGui import QApplication, QMainWindow, QComboBox, QPushButton, QTextEdit app = QApplication(sys.argv) win = QMainWindow() dock1 = XDockWidget("1st dockwidget", win) dock1.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) combo = QComboBox(dock1) dock1.setWidget(combo) win.addDockWidget(Qt.LeftDockWidgetArea, dock1) dock2 = XDockWidget("2nd dockwidget") button = QPushButton("Hello, world!", dock2) dock2.setWidget(button) win.addDockWidget(Qt.RightDockWidgetArea, dock2) edit = QTextEdit(win) win.setCentralWidget(edit) win.resize(640, 480) win.show() app.exec_()
except: import traceback traceback.print_exc() if self.cover_flow_syncing_enabled: QTimer.singleShot(500, self.cover_flow_do_sync) def sync_listview_to_cf(self, row): self.cf_last_updated_at = time.time() def main(args=sys.argv): return 0 if __name__ == '__main__': from PyQt4.QtGui import QApplication, QMainWindow app = QApplication([]) w = QMainWindow() cf = CoverFlow() cf.resize(int(available_width() / 1.5), available_height() - 60) w.resize(cf.size() + QSize(30, 20)) path = sys.argv[1] model = FileSystemImages(sys.argv[1]) cf.currentChanged[int].connect(model.currentChanged) cf.setImages(model) w.setCentralWidget(cf) w.show() cf.setFocus(Qt.OtherFocusReason) sys.exit(app.exec_())
grid_path = None grid_data_path = None polyline_root_path = None grid_path = "/d/proj/bg/enkf/ErtTestData/ECLIPSE/Mariner2/input/grids/maureen.grid.42" grid_data_path = "/d/proj/bg/enkf/ErtTestData/ECLIPSE/Mariner2/output/maureen.regions" if len(sys.argv) == 4: grid_path = sys.argv[1] grid_data_path = sys.argv[2] polyline_root_path = sys.argv[3] app = QApplication(["Slice Viewer"]) window = QMainWindow() window.resize(1024, 768) textures, bounds, nx, ny, nz, data_range , faults = createDataStructures(grid_path, grid_data_path , polyline_root_path) polylines = readPolylines(root_path=polyline_root_path) color_scales = createColorScales() textures["color_scale"] = color_scales[color_scales.keys()[0]] viewer = SliceViewer(textures=textures, volume_bounds=bounds, color_scales=color_scales, data_range=data_range, polylines=polylines , faults = faults) viewer.setSliceSize(width=nx, height=ny) slice_settings = SliceSettingsWidget(max_slice_count=nz, color_scales=color_scales.keys()) slice_settings.inactiveCellsHidden.connect(viewer.hideInactiveCells) slice_settings.currentSliceChanged.connect(viewer.setCurrentSlice)
import signal import sys #from PyMata.pymata import PyMata from PyQt4.QtGui import QApplication, QMainWindow, QPushButton,QVBoxLayout, QWidget, QTextEdit app = QApplication([]) button_convert = QPushButton("Convert order") mainwindow = QMainWindow() mainwindow.resize(230,400) mainwindow.setWindowTitle("Puuri abi") vbox = QVBoxLayout() vbox.addStretch(1) textedit = QTextEdit("First part") textedit2 = QTextEdit("Second part") textedit3 = QTextEdit(" ") vbox.addWidget(textedit) vbox.addWidget(textedit2) vbox.addWidget(textedit3) vbox.addWidget(button_convert) container = QWidget() container.setLayout(vbox) mainwindow.setCentralWidget(container) mainwindow.show() def convert_handler(): value = textedit2.toPlainText() #print(value)
series = QBarSeries() series.append(set0) series.append(set1) series.append(set2) series.append(set3) series.append(set4) chart = QChart() chart.addSeries(series) chart.setTitle("Simple barchart example") chart.createDefaultAxes() categories = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"] axis = QBarCategoriesAxis() axis.append(categories) chart.setAxisX(axis, series) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) window = QMainWindow() window.setCentralWidget(chartView) window.resize(400, 300) window.show() sys.exit(app.exec_())
class MainGUI(QObject): """ Class MainGUI uses PyQt elements to build up the main gui with all the gui elements of trees, editors, menu and so on. @author: ssimons """ MAIN_TREE = True SECOND_TREE = False signal_treeview1_expand_all = pyqtSignal() signal_treeview2_expand_all = pyqtSignal() signal_treeview1_collapse_all = pyqtSignal() signal_treeview2_collapse_all = pyqtSignal() signal_treeview1_clicked = pyqtSignal() signal_treeview2_clicked = pyqtSignal() signal_editor_of_tree1_clear = pyqtSignal() signal_editor_of_tree2_clear = pyqtSignal() def __init__(self): """ Initializes the gui elements """ super(MainGUI, self).__init__() app = QApplication(sys.argv) self.window = QWidget() self._conf = self._config_read_config_from_file_or_new() self.text_output_1 = QTextEdit() self.text_output_1_string = QString() self.text_output_2 = QTextEdit() self.text_output_2_string = QString() self.widget_right_window = QWidget() self.main_window = QMainWindow() self.tree_main = Tree(self._conf) self.tree_model_main = TreeModel(self.tree_main) self.tree_second = Tree(self._conf) self.tree_model_second = TreeModel(self.tree_second) self._init_gui() self.gui_menu = GuiMenu(self. tree_main, self.tree_second, self._conf, self.widget_right_window, self.main_window, SignalWrapper(self.signal_treeview1_expand_all, self.signal_treeview2_expand_all, self.signal_treeview1_collapse_all, self.signal_treeview2_collapse_all, self.signal_treeview1_clicked, self.signal_treeview2_clicked, self.signal_editor_of_tree1_clear, self.signal_editor_of_tree2_clear)) self.main_window.setMenuBar(self.gui_menu) gui_helper.open_last_opened_file_when_configured(self._conf, self.main_window, self.tree_main) self.main_window.show() app.exec_() def _init_gui(self): """ Initializes some widgets and delegates tree initializing to another function """ self.text_output_1.setWindowTitle("Output Tree1") self.text_output_1.setReadOnly(True) self.text_output_2.setWindowTitle("Output Tree2") self.text_output_2.setReadOnly(True) self.signal_editor_of_tree1_clear.connect(self.text_output_1.clear) self.signal_editor_of_tree2_clear.connect(self.text_output_2.clear) self.main_window.setCentralWidget(self.window) self.main_window.resize(500, 300) widget_left_window = QWidget() widget_left_window.setLayout( self._initialize_create_tree(self.MAIN_TREE, self.tree_model_main, self.text_output_1)) self.widget_right_window.setLayout( self._initialize_create_tree(self.SECOND_TREE, self.tree_model_second, self.text_output_2)) self.widget_right_window.hide() widget_two_windows = QSplitter() layout_two_windows = QHBoxLayout() layout_two_windows.addWidget(widget_left_window) layout_two_windows.addWidget(self.widget_right_window) widget_two_windows.setLayout(layout_two_windows) self.window.setLayout(layout_two_windows) def _initialize_create_tree(self, is_main_tree, tree_model_instance, text_output_instance): """ Creates gui elements for the tree-gui given as parameter. Also binds the given text output to this tree. Will be used for both tree widgets. @param is_main_tree: to differ between main and second tree. @param tree_model_instance: TreeModel object that should be used. @param text_output_instance: QTextEdit object which should be used / bind with the tree wiget. """ widget_tree_and_editor = QSplitter() layout_tree_and_editor = QHBoxLayout() tree_view = QTreeView() tree_view.setModel(tree_model_instance) tree_view.clicked[QModelIndex].connect( lambda: self.tree_element_clicked_event(is_main_tree)) if is_main_tree == self.SECOND_TREE: self.signal_treeview2_expand_all.connect(tree_view.expandAll) self.signal_treeview2_collapse_all.connect(tree_view.collapseAll) self.signal_treeview2_clicked.connect( lambda: tree_view.clicked.emit(QModelIndex())) else: self.signal_treeview1_expand_all.connect(tree_view.expandAll) self.signal_treeview1_collapse_all.connect(tree_view.collapseAll) self.signal_treeview1_clicked.connect( lambda: tree_view.clicked.emit(QModelIndex())) layout_tree_and_editor.addWidget(tree_view) layout_tree_and_editor.addWidget(text_output_instance) widget_tree_and_editor.setLayout(layout_tree_and_editor) layout_window = QVBoxLayout() layout_window.addWidget(widget_tree_and_editor) return layout_window def tree_element_clicked_event(self, is_main_tree): """ Action to display information of all selected tree elements in the text area. Selected means that the checkboxes of the tree element is checked. @param is_main_tree: to differ between main and second tree. """ if is_main_tree == self.SECOND_TREE: tree_operations.show_data_text_of_checked_tree_elements( self.tree_second.get_root_elements(), self._conf, self.text_output_2, self.text_output_2_string) else: tree_operations.show_data_text_of_checked_tree_elements( self.tree_main.get_root_elements(), self._conf, self.text_output_1, self.text_output_1_string) def _config_read_config_from_file_or_new(self): """Opens configuration from file - or if isn't possible return a new one""" config_filename = Configuration.CONFIG_FILENAME if not os.path.isfile(config_filename): logging.debug("configuration file %s doesn't exist.", config_filename) QMessageBox.information(self.window, "Info", '''No configuration file (''' + config_filename + ''') found. The default configuration is used. Change it in the configuration window (see menu View - Help). Afterwards a text file should be opened (menu MainFile - Open file).''') return Configuration() try: #try to open saved configuration and use it conf = Configuration() conf.data = ConfigurationFileReader.read_config() return conf except IOError, exc: logging.info("Couldn't open configuration file. " + config_filename + "Use the default values.") logging.exception(exc) return Configuration()
class InteractiveVelocityPlot(VelocityPlot): """ Visual tool to help with fitting Voigt profiles to absorption lines in QSO spectra. """ def __init__(self, filename, transitions, wavelength, flux, error, continuum, redshift, **kwargs): # Main window: self.window = QMainWindow() # Host widget for plot, push button, and checkboxes: self.main_frame = QWidget() # Spectrum filename: self.filename = filename # Plotting options: self.options = kwargs # Optimise screen usage: if len(transitions) > 20: ncols = int(ceil(len(transitions) / 10)) else: ncols = int(ceil(len(transitions) / 5)) # Initialise plot: super(InteractiveVelocityPlot, self).__init__( transitions, ncols=ncols, aspect=0.45, **self.options['WINDOW']) # Attach canvas to host widget: self.canvas = FigureCanvasQTAgg(self) self.canvas.setParent(self.main_frame) # Text input/output: self.text_output = QTextEdit() # Push buttons: self.load_button = QPushButton('&Load') self.save_button = QPushButton('&Save') self.preview_button = QPushButton('&Preview') self.clear_button = QPushButton('&Clear') self.refresh_plot_button = QPushButton('&Refresh plot') self.plot_model_button = QPushButton('&Plot model') self.plot_all_models_button = QPushButton('&Plot all models') self.clear_models_button = QPushButton('&Clear models') self.runvpfit_button = QPushButton('&Run VPFIT') self.set_resolution = QPushButton('&Set resolution') self.help = QPushButton('&Help') self.quit = QPushButton('&Quit') # Checkboxes: self.cos_fuv_checkbox = QCheckBox('&use COS FUV LSF') self.cos_nuv_checkbox = QCheckBox('&use COS NUV LSF') self.include_checkbox = QCheckBox('&include previous') # Push button `clicked` connections: self.load_button.clicked.connect(self.on_load) self.save_button.clicked.connect(self.on_save) self.preview_button.clicked.connect(self.on_preview) self.clear_button.clicked.connect(self.on_clear) self.refresh_plot_button.clicked.connect(self.on_refresh) self.plot_model_button.clicked.connect(self.on_plot_model) self.plot_all_models_button.clicked.connect(self.on_plot_all_models) self.clear_models_button.clicked.connect(self.on_clear_models) self.runvpfit_button.clicked.connect(self.on_runvpfit) self.set_resolution.clicked.connect(self.on_resolution) self.help.clicked.connect(self.on_help) self.quit.clicked.connect(self.window.close) # Checkbox `stateChanged` connections: self.cos_fuv_checkbox.stateChanged.connect(self.on_cos_fuv_checkbox) self.cos_nuv_checkbox.stateChanged.connect(self.on_cos_nuv_checkbox) self.include_checkbox.stateChanged.connect(self.on_include_checkbox) # Set up grid layout: grid = QGridLayout() grid.setSpacing(10) # Add widgets: grid.addWidget(self.text_output, 1, 1, 4, 3) grid.addWidget(self.load_button, 1, 4) grid.addWidget(self.save_button, 2, 4) grid.addWidget(self.preview_button, 3, 4) grid.addWidget(self.clear_button, 4, 4) grid.addWidget(self.refresh_plot_button, 1, 5) grid.addWidget(self.plot_model_button, 2, 5) grid.addWidget(self.plot_all_models_button, 3, 5) grid.addWidget(self.clear_models_button, 4, 5) grid.addWidget(self.runvpfit_button, 1, 6) grid.addWidget(self.cos_fuv_checkbox, 2, 6) grid.addWidget(self.cos_nuv_checkbox, 3, 6) grid.addWidget(self.include_checkbox, 4, 6) grid.addWidget(self.set_resolution, 1, 7) grid.addWidget(self.help, 3, 7) grid.addWidget(self.quit, 4, 7) # Place plotting canvas above the options grid: vbox = QVBoxLayout() vbox.addWidget(self.canvas) vbox.addLayout(grid) # Set the layout to the host widget: self.main_frame.setLayout(vbox) # Store all static elements (can be very slow to re-draw these): self.canvas.draw() self.backgrounds = [self.canvas.copy_from_bbox(ax.bbox) for ax in self.axes] # Plot the data: self.plot_data(wavelength, flux, error, continuum, redshift, **self.options['DATA']) # Set the window title: self.window.setWindowTitle('vpguess z = {0:.3f}'.format(self.redshift)) # Give keyboard focus to the figure: self.canvas.setFocusPolicy(Qt.StrongFocus) self.canvas.setFocus() # Variable defaults: self.cos_fuv = False self.cos_nuv = False self.include = False self.last_loaded = None self.resolution = None # Keypress variables: self.previous_keypress = None self.previous_wavelength = None # Set up the key-press events: self.canvas.mpl_connect('key_press_event', self.on_keypress) # Set the main frame as the central widget: self.window.setCentralWidget(self.main_frame) # Resize the window so it will display the canvas with the # requested size: layout_height = vbox.sizeHint().height() layout_width = vbox.sizeHint().width() status_bar_height = self.window.statusBar().sizeHint().height() height = layout_height + status_bar_height self.window.resize(layout_width, height) # Re-do labels: del self.texts[:] self.text(0.45, 0.02, 'Velocity offset (km s$^{-1}$)') self.text(0.01, 0.57, 'Transmission', rotation=90) # Disable any existing callbacks: self.cids = dict() cids1 = list(self.canvas.callbacks.callbacks['key_press_event']) cids2 = list(self.canvas.callbacks.callbacks['button_press_event']) cids = cids1 + cids2 for cid in cids: self.canvas.callbacks.disconnect(cid) # Connect new callbacks: self.connect() def update_plot(self, redshift): # Restore background regions: [self.canvas.restore_region(background) for background in self.backgrounds] # Plot data: [data.pop(0).remove() for data in self.data] self.plot_data( self.wavelength, self.flux, self.error, self.continuum, redshift, **self.options['DATA']) # Draw the artists: for artists in self.data: for element in artists: ax = element.get_axes() ax.draw_artist(element) # Plot the models (if any): if self.options['MODEL']['absorbers'] is not None: self.plot_models(resolution=self.resolution, convolve_with_cos_fuv=self.cos_fuv, convolve_with_cos_nuv=self.cos_nuv, **self.options['MODEL']) # Draw the artists: for artists in self.models: for element in artists: ax = element.get_axes() ax.draw_artist(element) # Draw new panel labels: for i, transition in enumerate(self.transitions): ax = self.axes[self._ind[i]] transf = blended_transform_factory(ax.transAxes, ax.transData) name = transition.name # Use TeX fonts if specified: if self.usetex: name = name.split() if name[0][1].islower(): name = name[0][:2] + '$\;$\\textsc{' + \ name[0][2:].lower() + '} $\lambda$' + name[1] else: name = name[0][:1] + '$\;$\\textsc{' + \ name[0][1:].lower() + '} $\lambda$' + name[1] label = ax.text(0.03, 0.5, name, fontsize=self.label_fontsize, bbox=bbox, transform=transf) ax.draw_artist(label) # Update: self.canvas.update() self.window.setWindowTitle( 'vpguess z = {0:.3f}'.format(self.redshift)) @staticmethod def concatenate_results(): from glob import glob results = glob('*.result') with open('.all_results', 'wb') as combined: for result in results: with open(result, 'rb') as single: combined.write(single.read()) @pyqtSlot(str) def on_output(self, output): self.text_output.moveCursor(QTextCursor.End) self.text_output.insertPlainText(output) def on_load(self): self.text_output.clear() directory = os.getcwd() filename = QFileDialog.getOpenFileName( self.window, 'Select f26 file', directory) with open(filename, 'rb') as f26: self.text_output.setText(f26.read()) self.last_loaded = filename def on_save(self): directory = os.getcwd() filename, ok = QFileDialog.getSaveFileName( self.window, 'Save f26 file', directory) with open(filename, 'w') as f26: f26.write(str(self.text_output.toPlainText())) self.text_output.clear() self.last_loaded = None def on_preview(self): self.concatenate_results() with open('.f26_preview', 'wb') as preview: with open('.all_results', 'rb') as results: preview.write(str(self.text_output.toPlainText())) preview.write(results.read()) f26 = read_f26('.f26_preview') self.options['MODEL']['absorbers'] = f26.absorbers self.update_plot(self.redshift) def on_clear(self): self.text_output.clear() self.last_loaded = None def on_refresh(self): self.update_plot(self.redshift) def on_plot_model(self): directory = os.getcwd() filename = QFileDialog.getOpenFileName( self.window, 'Select f26 file', directory) f26 = read_f26(filename) self.options['MODEL']['absorbers'] = f26.absorbers if f26.absorbers is not None: self.update_plot(self.redshift) def on_plot_all_models(self): self.concatenate_results() f26 = read_f26('.all_results') self.options['MODEL']['absorbers'] = f26.absorbers if f26.absorbers is not None: self.update_plot(self.redshift) def on_clear_models(self): self.options['MODEL']['absorbers'] = None self.update_plot(self.redshift) def on_runvpfit(self): from .vpfit import run_vpfit directory = os.getcwd() if self.last_loaded is not None: filename = self.last_loaded if self.text_output.document().isModified(): with open(filename, 'w') as f26: f26.write(str(self.text_output.toPlainText())) else: filename = QFileDialog.getSaveFileName( self.window, 'Save f26 file', directory) with open(filename, 'w') as f26: f26.write(str(self.text_output.toPlainText())) self.concatenate_results() inc = '.all_results' if self.include else None self.text_output.clear() fwhm = self.resolution if self.resolution is not None else 10 run_vpfit(filename, inc, fwhm=fwhm, cos_fuv=self.cos_fuv, cos_nuv=self.cos_nuv) self.concatenate_results() f26 = read_f26('.all_results') self.options['MODEL']['absorbers'] = f26.absorbers if f26.absorbers is not None: self.update_plot(self.redshift) self.last_loaded = None def on_cos_fuv_checkbox(self, state): if state == Qt.Checked: self.cos_fuv = True else: self.cos_fuv = False def on_cos_nuv_checkbox(self, state): if state == Qt.Checked: self.cos_nuv = True else: self.cos_nuv = False def on_include_checkbox(self, state): if state == Qt.Checked: self.include = True else: self.include = False def on_resolution(self): resolution, ok = SpectralResolutionDialog.get_spectral_resolution( self.main_frame) if ok: self.resolution = resolution def on_help(self): QMessageBox.information(self.main_frame, 'Help', info, False) def on_buttonpress(self, event): if event.inaxes is None: return i = self.axes.index(event.inaxes) transition = self.transitions[np.where(self._ind == i)[0]] z = (1 + event.xdata / c_kms) * (1 + self.redshift) - 1 wavelength = transition.wavelength.value * (1 + z) isort = np.argsort(self.ticks['wavelength']) wavelengths = self.ticks['wavelength'][isort] transitions = self.ticks['transition'][isort] idx = wavelengths.searchsorted(wavelength) wavelength = wavelengths[idx] transition = atom.get_transition(transitions[idx]) z = wavelength / transition.wavelength.value - 1 message = '{0}, z = {1:.3f}'.format(transition.name, z) QMessageBox.information(self.main_frame, 'Transition', message, False) def on_keypress(self, event): if event.key == ' ' and event.inaxes is not None: z = self.redshift # Get amount to add to redshift: dz = (event.xdata / c_kms) * (1 + z) # Get new axis limits, if any: vmin, vmax = event.inaxes.get_xlim() self.vmin = min(0, vmin) self.vmax = max(0, vmax) self.update_plot(z + dz) if event.key == 'z': redshift, ok = QInputDialog.getText( self.main_frame, 'New Redshift', 'Enter redshift: ', False) if ok: self.update_plot(float(redshift)) if event.key == 'b': i = self.axes.index(event.inaxes) transition = self.transitions[np.where(self._ind == i)[0]] z = (1 + event.xdata / c_kms) * (1 + self.redshift) - 1 wavelength = transition.wavelength.value * (1 + z) if (self.previous_keypress == 'b' and self.previous_wavelength is not None): wmin = self.previous_wavelength wmax = wavelength if wmin > wmax: wmin, wmax = wmax, wmin print('%% {0} 1 {1:.3f} {2:.3f} vfwhm=10.0'.format( self.filename, wmin, wmax)) self.previous_keypress = None self.previous_wavelength = None else: self.previous_wavelength = wavelength if event.key == 'l': from ..calculations.absorption import logn_from_tau_peak i = self.axes.index(event.inaxes) transition = self.transitions[np.where(self._ind == i)[0]] z = (1 + event.xdata / c_kms) * (1 + self.redshift) - 1 wavelength = transition.wavelength.value * (1 + z) index = self.wavelength.searchsorted(wavelength) flux = self.flux[index - 1:index + 1] error = self.error[index - 1:index + 1] continuum = self.continuum[index - 1:index + 1] flux_norm = flux / continuum error_norm = error / continuum valid = (error_norm > 0) & ~np.isnan(flux_norm) if not any(valid): print('No good pixels!') return flux_norm = np.median(flux_norm[valid]) error_norm = np.median(error_norm[valid]) if flux_norm < error_norm: flux_norm = error_norm elif flux_norm > 1 - error_norm: flux_norm = 1 - error_norm b = 20 # assume 20 km/s tau = -np.log(flux_norm) logn = logn_from_tau_peak(transition, tau, b) print('{0:6s} {1:8.6f} 0.0 {2:4.1f} 0.0 {3:4.1f} 0.0'.format( transition.parent, z, b, logn)) if event.key == 'S': filename, ok = QInputDialog.getText( self.main_frame, 'Save Figure', 'Enter filename: ', False) if ok: self.savefig(filename) self.previous_keypress = event.key def connect(self): cids = dict() cids['key_press_event'] = self.canvas.mpl_connect( 'key_press_event', self.on_keypress) cids['button_press_event'] = self.canvas.mpl_connect( 'button_press_event', self.on_buttonpress) self.cids.update(cids)
try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s # WINDOW = tk.Tk() # WINDOW.title(WindowCons.EXE_NAME) # 设置名称 # WINDOW.geometry(WindowCons.WINDOW_SIZE) # 设置初始窗口大小 APP = QApplication(sys.argv) WINDOW = QMainWindow() WINDOW.setObjectName(_fromUtf8("MainWindow")) WINDOW.resize(960, 540) CENTRAL_WIDGET = QWidget(WINDOW) CENTRAL_WIDGET.setObjectName(_fromUtf8("centralwidget")) # def callback(): # """关闭回调""" # if messagebox.askokcancel("Quit", "Do you really wish to quit?"): # WINDOW.destroy() # canvas = tk.Canvas(WINDOW, width=900, height=500, bd=0, highlightthickness=0) # imgpath = './resource/backgroud.png' # img = Image.open(imgpath) # photo = ImageTk.PhotoImage(img) # # canvas.create_image(900, 500, image=photo)
def main(): ns = _parseCommandLine() _fixSysPath(ns.binary) import qutepart # after correct sys.path has been set with open(ns.file) as file: text = unicode(file.read(), 'utf8') if ns.debug: logging.getLogger('qutepart').setLevel(logging.DEBUG) app = QApplication(sys.argv) window = QMainWindow() qpart = qutepart.Qutepart() window.setCentralWidget(qpart) firstLine = text.splitlines()[0] if text else None qpart.detectSyntax(sourceFilePath=ns.file, firstLine=firstLine) qpart.lineLengthEdge = 20 qpart.drawIncorrectIndentation = True qpart.drawAnyWhitespace = False qpart.indentUseTabs = True qpart.text = text qpart.setWindowTitle(ns.file) menu = {'File': ('printAction',), 'Bookmarks': ('toggleBookmarkAction', 'nextBookmarkAction', 'prevBookmarkAction'), 'Navigation':('scrollUpAction', 'scrollDownAction', 'selectAndScrollUpAction', 'selectAndScrollDownAction', ), 'Indentation':('increaseIndentAction', 'decreaseIndentAction', 'autoIndentLineAction', 'indentWithSpaceAction', 'unIndentWithSpaceAction'), 'Lines': ('moveLineUpAction', 'moveLineDownAction', 'deleteLineAction', 'copyLineAction', 'pasteLineAction', 'cutLineAction', 'duplicateLineAction'), 'Edit' : ('invokeCompletionAction', 'undoAction', 'redoAction' ) } for k, v in menu.items(): menuObject = window.menuBar().addMenu(k) for actionName in v: menuObject.addAction(getattr(qpart, actionName)) qpart.userWarning.connect(lambda text: window.statusBar().showMessage(text, 3000)) window.resize(800, 600) window.show() from PyQt4.QtCore import QTimer if ns.quit: QTimer.singleShot(0, app.quit) return app.exec_()