コード例 #1
0
ファイル: try_mouses.py プロジェクト: Ascaf0/synaptiks
def main():
    app = QApplication(sys.argv)

    window = QMainWindow()
    splitter = QSplitter(window)
    window.setCentralWidget(splitter)
    left_view = MouseDevicesView(window)
    left_view.checkedDevicesChanged.connect(partial(show, 'left:'))
    right_view = MouseDevicesView(window)
    right_view.checkedDevicesChanged.connect(partial(show, 'right:'))
    splitter.addWidget(left_view)
    splitter.addWidget(right_view)

    def _move_checked_state(source, dest):
        checked = source.property('checkedDevices').toPyObject()
        dest.setProperty('checkedDevices', checked)

    toolbar = window.addToolBar('Actions')
    move_selection_left = QAction(
        QIcon.fromTheme('arrow-left'), 'Moved checked state left', window,
        triggered=partial(_move_checked_state, right_view, left_view))
    move_selection_right = QAction(
        QIcon.fromTheme('arrow-right'), 'Moved checked state right', window,
        triggered=partial(_move_checked_state, left_view, right_view))
    toolbar.addAction(move_selection_left)
    toolbar.addAction(move_selection_right)

    window.show()
    app.exec_()
コード例 #2
0
ファイル: try_mouses.py プロジェクト: adaptee/synaptiks
def main():
    app = QApplication(sys.argv)

    window = QMainWindow()
    splitter = QSplitter(window)
    window.setCentralWidget(splitter)
    left_view = MouseDevicesView(window)
    left_view.checkedDevicesChanged.connect(partial(show, 'left:'))
    right_view = MouseDevicesView(window)
    right_view.checkedDevicesChanged.connect(partial(show, 'right:'))
    splitter.addWidget(left_view)
    splitter.addWidget(right_view)

    def _move_checked_state(source, dest):
        checked = source.property('checkedDevices').toPyObject()
        dest.setProperty('checkedDevices', checked)

    toolbar = window.addToolBar('Actions')
    move_selection_left = QAction(QIcon.fromTheme('arrow-left'),
                                  'Moved checked state left',
                                  window,
                                  triggered=partial(_move_checked_state,
                                                    right_view, left_view))
    move_selection_right = QAction(QIcon.fromTheme('arrow-right'),
                                   'Moved checked state right',
                                   window,
                                   triggered=partial(_move_checked_state,
                                                     left_view, right_view))
    toolbar.addAction(move_selection_left)
    toolbar.addAction(move_selection_right)

    window.show()
    app.exec_()
コード例 #3
0
ファイル: test_dropshadow.py プロジェクト: 675801717/orange3
    def test1(self):
        class FT(QToolBar):
            def paintEvent(self, e):
                pass

        w = QMainWindow()
        ftt, ftb = FT(), FT()
        ftt.setFixedHeight(15)
        ftb.setFixedHeight(15)

        w.addToolBar(Qt.TopToolBarArea, ftt)
        w.addToolBar(Qt.BottomToolBarArea, ftb)

        f = dropshadow.DropShadowFrame()
        te = QTextEdit()
        c = QWidget()
        c.setLayout(QVBoxLayout())
        c.layout().setContentsMargins(20, 0, 20, 0)
        c.layout().addWidget(te)
        w.setCentralWidget(c)
        f.setWidget(te)
        f.radius = 15
        f.color = QColor(Qt.blue)
        w.show()

        self.singleShot(3000, lambda: f.setColor(Qt.red))
        self.singleShot(4000, lambda: f.setRadius(30))
        self.singleShot(5000, lambda: f.setRadius(40))

        self.app.exec_()
コード例 #4
0
ファイル: test_dropshadow.py プロジェクト: yisuax11/orange2
    def test1(self):
        class FT(QToolBar):
            def paintEvent(self, e):
                pass

        w = QMainWindow()
        ftt, ftb = FT(), FT()
        ftt.setFixedHeight(15)
        ftb.setFixedHeight(15)

        w.addToolBar(Qt.TopToolBarArea, ftt)
        w.addToolBar(Qt.BottomToolBarArea, ftb)

        f = dropshadow.DropShadowFrame()
        te = QTextEdit()
        c = QWidget()
        c.setLayout(QVBoxLayout())
        c.layout().setContentsMargins(20, 0, 20, 0)
        c.layout().addWidget(te)
        w.setCentralWidget(c)
        f.setWidget(te)
        f.radius = 15
        f.color = QColor(Qt.blue)
        w.show()

        self.singleShot(3000, lambda: f.setColor(Qt.red))
        self.singleShot(4000, lambda: f.setRadius(30))
        self.singleShot(5000, lambda: f.setRadius(40))

        self.app.exec_()
コード例 #5
0
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)
コード例 #6
0
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())
コード例 #7
0
ファイル: mainwindow.py プロジェクト: egyilmaz/SimFrames
	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_()
コード例 #8
0
ファイル: main.py プロジェクト: drimer/AccessDatesList
def startApp():
    app = QApplication(sys.argv)
    mainWindow = QMainWindow()
    datesWindow = AccessDatesList(mainWindow, rootDir='/home/')
    mainWindow.setCentralWidget(datesWindow)
    mainWindow.setMinimumWidth(500)
    mainWindow.setMinimumHeight(500)
    mainWindow.show()
    app.exec_()
コード例 #9
0
ファイル: pyqt4.py プロジェクト: brodybits/pyjs
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())
コード例 #10
0
ファイル: Televideo.py プロジェクト: ZeeD/unusefulscripts
def gui(argv, pagina):
    from PyQt4.QtGui import QApplication, QMainWindow, QTextEdit

    app = QApplication(argv)
    mainWindow = QMainWindow()
    textEdit = QTextEdit()

    mainWindow.setCentralWidget(textEdit)
    mainWindow.show()
    textEdit.setReadOnly(True)
    textEdit.setText(analizza(pagina))

    raise SystemExit(app.exec_())
コード例 #11
0
ファイル: histo.py プロジェクト: drphilmarshall/glue
def main():

    app = QApplication(sys.argv)
    win = QMainWindow()

    data = example_data.simple_image()
    dc = DataCollection([data])
    histo_client = HistogramWidget(dc)

    hub = Hub(dc, histo_client)
    win.setCentralWidget(histo_client)
    win.show()
    sys.exit(app.exec_())
コード例 #12
0
def main():

    app = QApplication(sys.argv)
    win = QMainWindow()

    data = example_data.simple_image()
    dc = DataCollection([data])
    histo_client = HistogramWidget(dc)

    hub = Hub(dc, histo_client)
    win.setCentralWidget(histo_client)
    win.show()
    sys.exit(app.exec_())
コード例 #13
0
def main():
    app = QApplication(sys.argv)

    window = QMainWindow()
    central_widget = QWidget(window)

    start_action = QAction('Start', window)
    stop_action = QAction('Stop', window)
    toolbar = window.addToolBar('Monitor')
    toolbar.addAction(start_action)
    toolbar.addAction(stop_action)

    central_layout = QVBoxLayout(central_widget)

    monitor_name = QLabel(central_widget)
    central_layout.addWidget(monitor_name)

    state_label = QLabel(central_widget)
    central_layout.addWidget(state_label)

    combo_box = QComboBox(central_widget)
    items = [('No keys', AbstractKeyboardMonitor.IGNORE_NO_KEYS),
             ('Modifiers', AbstractKeyboardMonitor.IGNORE_MODIFIER_KEYS),
             ('Modifier combos',
              AbstractKeyboardMonitor.IGNORE_MODIFIER_COMBOS)]
    for label, userdata in items:
        combo_box.addItem(label, userdata)

    def _update_ignore_keys(index):
        monitor.keys_to_ignore = combo_box.itemData(index).toPyObject()

    combo_box.currentIndexChanged[int].connect(_update_ignore_keys)
    central_layout.addWidget(combo_box)

    central_widget.setLayout(central_layout)
    window.setCentralWidget(central_widget)

    monitor = create_keyboard_monitor(window)
    monitor_name.setText('Using monitor class {0}'.format(
        monitor.__class__.__name__))
    monitor.typingStarted.connect(partial(state_label.setText, 'typing'))
    monitor.typingStopped.connect(partial(state_label.setText, 'not typing'))
    start_action.triggered.connect(monitor.start)
    stop_action.triggered.connect(monitor.stop)
    stop_action.setEnabled(False)
    monitor.started.connect(partial(start_action.setEnabled, False))
    monitor.started.connect(partial(stop_action.setEnabled, True))
    monitor.stopped.connect(partial(start_action.setEnabled, True))
    monitor.stopped.connect(partial(stop_action.setEnabled, False))
    window.show()
    app.exec_()
コード例 #14
0
def main():
    app = QApplication(sys.argv)

    window = QMainWindow()
    central_widget = QWidget(window)

    start_action = QAction('Start', window)
    stop_action = QAction('Stop', window)
    toolbar = window.addToolBar('Monitor')
    toolbar.addAction(start_action)
    toolbar.addAction(stop_action)

    central_layout = QVBoxLayout(central_widget)

    monitor_name = QLabel(central_widget)
    central_layout.addWidget(monitor_name)

    state_label = QLabel(central_widget)
    central_layout.addWidget(state_label)

    combo_box = QComboBox(central_widget)
    items = [
        ('No keys', AbstractKeyboardMonitor.IGNORE_NO_KEYS),
        ('Modifiers', AbstractKeyboardMonitor.IGNORE_MODIFIER_KEYS),
        ('Modifier combos', AbstractKeyboardMonitor.IGNORE_MODIFIER_COMBOS)]
    for label, userdata in items:
        combo_box.addItem(label, userdata)

    def _update_ignore_keys(index):
        monitor.keys_to_ignore = combo_box.itemData(index).toPyObject()

    combo_box.currentIndexChanged[int].connect(_update_ignore_keys)
    central_layout.addWidget(combo_box)

    central_widget.setLayout(central_layout)
    window.setCentralWidget(central_widget)

    monitor = create_keyboard_monitor(window)
    monitor_name.setText('Using monitor class {0}'.format(
        monitor.__class__.__name__))
    monitor.typingStarted.connect(partial(state_label.setText, 'typing'))
    monitor.typingStopped.connect(partial(state_label.setText, 'not typing'))
    start_action.triggered.connect(monitor.start)
    stop_action.triggered.connect(monitor.stop)
    stop_action.setEnabled(False)
    monitor.started.connect(partial(start_action.setEnabled, False))
    monitor.started.connect(partial(stop_action.setEnabled, True))
    monitor.stopped.connect(partial(start_action.setEnabled, True))
    monitor.stopped.connect(partial(stop_action.setEnabled, False))
    window.show()
    app.exec_()
コード例 #15
0
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())
コード例 #16
0
def main():
    """ Display a layer tree """
    from PyQt4.QtGui import QApplication, QMainWindow
    import sys

    hub = glue.Hub()
    app = QApplication(sys.argv)
    win = QMainWindow()
    ltw = LayerTreeWidget()
    ltw.register_to_hub(hub)
    ltw.data_collection.register_to_hub(hub)
    win.setCentralWidget(ltw)
    win.show()
    sys.exit(app.exec_())
コード例 #17
0
ファイル: layertree.py プロジェクト: drphilmarshall/glue
def main():
    """ Display a layer tree """
    from PyQt4.QtGui import QApplication, QMainWindow
    import sys

    hub = glue.Hub()
    app = QApplication(sys.argv)
    win = QMainWindow()
    ltw = LayerTreeWidget()
    ltw.register_to_hub(hub)
    ltw.data_collection.register_to_hub(hub)
    win.setCentralWidget(ltw)
    win.show()
    sys.exit(app.exec_())
コード例 #18
0
ファイル: main.py プロジェクト: eswald/squall
def main():
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    
    Tripane = QSplitter(MainWindow)
    tripane = Ui_Tripane()
    tripane.setupUi(Tripane)
    MainWindow.setCentralWidget(Tripane)
    
    ui.actionConnect.triggered.connect(lambda *args: populate(tripane.treeView))
    
    MainWindow.show()
    sys.exit(app.exec_())
コード例 #19
0
class PropertyViewTestCase(unittest.TestCase):
    def testExample(self):
        logging.debug(self.__class__.__name__ + ': testExample()')
        self.app = QApplication(sys.argv)
        self.window = QMainWindow()
        self.window.setWindowTitle("test PropertyView")
        self.app.setActiveWindow(self.window)
        self.window.show()
        self.propertyView = PropertyView(self.window)
        self.window.setCentralWidget(self.propertyView)
        self.propertyView.setDataAccessor(TestDataAccessor())
        self.propertyView.setDataObject("particle1")
        self.propertyView.updateContent()
        if not hasattr(unittest, "NO_GUI_TEST"):
            self.app.exec_()
コード例 #20
0
ファイル: testPropertyView.py プロジェクト: Andrej-CMS/cmssw
class PropertyViewTestCase(unittest.TestCase):
    def testExample(self):
        logging.debug(self.__class__.__name__ +': testExample()')
        self.app = QApplication(sys.argv)
        self.window= QMainWindow()
        self.window.setWindowTitle("test PropertyView")
        self.app.setActiveWindow(self.window)
        self.window.show()
        self.propertyView=PropertyView(self.window)
        self.window.setCentralWidget(self.propertyView)
        self.propertyView.setDataAccessor(TestDataAccessor())
        self.propertyView.setDataObject("particle1")
        self.propertyView.updateContent()
        if not hasattr(unittest,"NO_GUI_TEST"):
            self.app.exec_()
コード例 #21
0
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_())
コード例 #22
0
ファイル: __init__.py プロジェクト: Brainsciences/luminoso
 def create_mainwindow(self):
     """
     Create a QMainWindow instance containing this plugin
     Note: this method is currently not used
     """
     mainwindow = QMainWindow()
     mainwindow.setAttribute(Qt.WA_DeleteOnClose)
     icon = self.get_widget_icon()
     if isinstance(icon, basestring):
         icon = get_icon(icon)
     mainwindow.setWindowIcon(icon)
     mainwindow.setWindowTitle(self.get_widget_title())
     mainwindow.setCentralWidget(self)
     self.refresh()
     return mainwindow
コード例 #23
0
ファイル: cover_flow.py プロジェクト: Hainish/calibre
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_())
コード例 #24
0
class ToolBoxContainerTestCase(unittest.TestCase):
    def testExample(self):
        logging.debug(self.__class__.__name__ +': testExample()')
        self.app = QApplication(sys.argv)
        self.window = QMainWindow()
        self.window.setWindowTitle("test ToolBoxContainer")
        self.app.setActiveWindow(self.window)
        self.window.show()
        container = ToolBoxContainer(self.window)
        self.window.setCentralWidget(container)
        container.addWidget(QTextEdit("ganz viel text\n mit zeilenumbruechen\n."))
        container.addWidget(QTextEdit("anderer inhalt."))
        container.show()
        if not hasattr(unittest,"NO_GUI_TEST"):
            self.app.exec_()
コード例 #25
0
ファイル: testTreeView.py プロジェクト: Andrej-CMS/cmssw
class TreeViewTestCase(unittest.TestCase):
    def testExample(self):
        logging.debug(self.__class__.__name__ +': testExample()')
        self.app = QApplication(sys.argv)
        self.window= QMainWindow()
        self.window.setWindowTitle("test TreeView")
        self.app.setActiveWindow(self.window)
        self.window.show()
        self.treeView = TreeView(self.window)
        self.window.setCentralWidget(self.treeView)
        accessor=TestDataAccessor()
        self.treeView.setDataAccessor(accessor)
        self.treeView.setDataObjects(accessor.topLevelObjects())
        self.treeView.updateContent()
        if not hasattr(unittest,"NO_GUI_TEST"):
            self.app.exec_()
コード例 #26
0
class TreeViewTestCase(unittest.TestCase):
    def testExample(self):
        logging.debug(self.__class__.__name__ + ': testExample()')
        self.app = QApplication(sys.argv)
        self.window = QMainWindow()
        self.window.setWindowTitle("test TreeView")
        self.app.setActiveWindow(self.window)
        self.window.show()
        self.treeView = TreeView(self.window)
        self.window.setCentralWidget(self.treeView)
        accessor = TestDataAccessor()
        self.treeView.setDataAccessor(accessor)
        self.treeView.setDataObjects(accessor.topLevelObjects())
        self.treeView.updateContent()
        if not hasattr(unittest, "NO_GUI_TEST"):
            self.app.exec_()
コード例 #27
0
ファイル: gui.py プロジェクト: ps-aux/algos
    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)
コード例 #28
0
ファイル: scatter.py プロジェクト: drphilmarshall/glue
def main():

    app = QApplication(sys.argv)
    win = QMainWindow()

    data, data2, s, s2 = glue.example_data.pipe()
    dc = glue.DataCollection([data, data2])
    scatter_client = ScatterWidget(dc)
    message_client = MessageWidget()
    hub = glue.Hub(data, data2, dc, scatter_client,
                   data.edit_subset, message_client)
#    scatter_client.add_layer(data)
#    scatter_client.add_layer(data2)
    win.setCentralWidget(scatter_client)
    win.show()
    #message_client.show()
    sys.exit(app.exec_())
コード例 #29
0
ファイル: scatter.py プロジェクト: hihihippp/glue
def main():

    app = QApplication(sys.argv)
    win = QMainWindow()

    data, data2, s, s2 = glue.example_data.pipe()
    dc = glue.DataCollection([data, data2])
    scatter_client = ScatterWidget(dc)
    message_client = MessageWidget()
    hub = glue.Hub(data, data2, dc, scatter_client, data.edit_subset,
                   message_client)
    #    scatter_client.add_layer(data)
    #    scatter_client.add_layer(data2)
    win.setCentralWidget(scatter_client)
    win.show()
    #message_client.show()
    sys.exit(app.exec_())
コード例 #30
0
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_()
コード例 #31
0
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_()
コード例 #32
0
ファイル: ide_test.py プロジェクト: YingfangZhou/ert
def main():
    if len(sys.argv) == 1:
        print("Missing configuration file!")
        sys.exit(1)

    QApplication.setGraphicsSystem("raster")
    app = QApplication(sys.argv) #Early so that QT is initialized before other imports


    main_window = QMainWindow()

    central_widget = QWidget()
    main_window.setCentralWidget(central_widget)
    layout = QVBoxLayout()
    central_widget.setLayout(layout)

    search = SearchBox()


    ide = IdePanel()

    layout.addWidget(search)
    layout.addWidget(ide, 1)


    path = sys.argv[1]
    with open(path) as f:
        config_file = f.read()

    highlighter = KeywordHighlighter(ide.document())

    search.filterChanged.connect(highlighter.setSearchString)

    ide.document().setPlainText(config_file)

    cursor = ide.textCursor()
    cursor.setPosition(0)
    ide.setTextCursor(cursor)
    ide.setFocus()

    main_window.show()

    sys.exit(app.exec_())
コード例 #33
0
ファイル: main.py プロジェクト: Garjy/edis
    def __init__(self):
        QMainWindow.__init__(self)
        # Esto para tener widgets laterales en full height,
        window = QMainWindow(self)
        self.setWindowTitle("{" + ui.__edis__ + "}")
        self.setMinimumSize(750, 500)
        # Se cargan las dimensiones de la ventana
        if settings.get_setting("window/show-maximized"):
            self.setWindowState(Qt.WindowMaximized)
        else:
            size = settings.get_setting("window/size")
            position = settings.get_setting("window/position")
            self.resize(size)
            self.move(position)
        # Toolbars
        self.toolbar = QToolBar(self)
        self.toolbar.setObjectName("toolbar")
        toggle_action = self.toolbar.toggleViewAction()
        toggle_action.setText(self.tr("Toolbar"))
        self.toolbar.setIconSize(QSize(24, 24))
        self.toolbar.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.addToolBar(Qt.RightToolBarArea, self.toolbar)
        Edis.load_component("toolbar", self.toolbar)
        # Animated property
        self.setDockOptions(QMainWindow.AnimatedDocks)
        # Menú
        menu_bar = self.menuBar()
        self.setup_menu(menu_bar)
        # Barra de estado
        self.status_bar = Edis.get_component("status_bar")
        self.setStatusBar(self.status_bar)
        # Widget central
        central = self._load_ui(window)
        window.setCentralWidget(central)
        window.setWindowFlags(Qt.Widget)
        self.setCentralWidget(window)

        Edis.load_component("edis", self)
        # Comprobar nueva versión
        if settings.get_setting("general/check-updates"):
            self.noti = system_tray.NotificacionActualizacion()
            self.noti.show()
コード例 #34
0
ファイル: main.py プロジェクト: yoshitomimaehara/edis
    def __init__(self):
        QMainWindow.__init__(self)
        # Esto para tener widgets laterales en full height,
        window = QMainWindow(self)
        self.setWindowTitle('{' + ui.__edis__ + '}')
        self.setMinimumSize(750, 500)
        # Se cargan las dimensiones de la ventana
        if settings.get_setting('window/show-maximized'):
            self.setWindowState(Qt.WindowMaximized)
        else:
            size = settings.get_setting('window/size')
            position = settings.get_setting('window/position')
            self.resize(size)
            self.move(position)
        # Toolbars
        self.toolbar = QToolBar(self)
        self.toolbar.setObjectName("toolbar")
        toggle_action = self.toolbar.toggleViewAction()
        toggle_action.setText(self.tr("Toolbar"))
        self.toolbar.setIconSize(QSize(24, 24))
        self.toolbar.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.addToolBar(Qt.RightToolBarArea, self.toolbar)
        Edis.load_component("toolbar", self.toolbar)
        # Animated property
        self.setDockOptions(QMainWindow.AnimatedDocks)
        # Menú
        menu_bar = self.menuBar()
        self.setup_menu(menu_bar)
        # Barra de estado
        self.status_bar = Edis.get_component("status_bar")
        self.setStatusBar(self.status_bar)
        # Widget central
        central = self._load_ui(window)
        window.setCentralWidget(central)
        window.setWindowFlags(Qt.Widget)
        self.setCentralWidget(window)

        Edis.load_component("edis", self)
        # Comprobar nueva versión
        if settings.get_setting('general/check-updates'):
            self.noti = system_tray.NotificacionActualizacion()
            self.noti.show()
コード例 #35
0
ファイル: image.py プロジェクト: andyras/glue
def main():

    app = QApplication(sys.argv)
    win = QMainWindow()

    #data, subset = glue.example_data.simple_cube()
    d2, s2 = glue.example_data.simple_image()

    #dc = glue.DataCollection([data, d2, data])
    dc = glue.DataCollection([d2])
    image_client = ImageWidget(dc)
    message_client = MessageWidget()

    hub = glue.Hub(dc, image_client, message_client)
    win.setCentralWidget(image_client)
    win.show()
    message_client.show()
    #image_client.client.set_norm(1, 2000)
    #image_client.client.set_cmap('hot')
    sys.exit(app.exec_())
コード例 #36
0
ファイル: ide_test.py プロジェクト: danielfmva/ert
def main():
    if len(sys.argv) == 1:
        print("Missing configuration file!")
        sys.exit(1)

    QApplication.setGraphicsSystem("raster")
    app = QApplication(
        sys.argv)  #Early so that QT is initialized before other imports

    main_window = QMainWindow()

    central_widget = QWidget()
    main_window.setCentralWidget(central_widget)
    layout = QVBoxLayout()
    central_widget.setLayout(layout)

    search = SearchBox()

    ide = IdePanel()

    layout.addWidget(search)
    layout.addWidget(ide, 1)

    path = sys.argv[1]
    with open(path) as f:
        config_file = f.read()

    highlighter = KeywordHighlighter(ide.document())

    search.filterChanged.connect(highlighter.setSearchString)

    ide.document().setPlainText(config_file)

    cursor = ide.textCursor()
    cursor.setPosition(0)
    ide.setTextCursor(cursor)
    ide.setFocus()

    main_window.show()

    sys.exit(app.exec_())
コード例 #37
0
ファイル: test_dock.py プロジェクト: yisuax11/orange2
    def test_dock_mainwinow(self):
        mw = QMainWindow()
        dock = CollapsibleDockWidget()
        w1 = QTextEdit()

        w2 = QToolButton()
        w2.setFixedSize(38, 200)

        dock.setExpandedWidget(w1)
        dock.setCollapsedWidget(w2)

        mw.addDockWidget(Qt.LeftDockWidgetArea, dock)
        mw.setCentralWidget(QTextEdit())
        mw.show()

        def toogle():
            dock.setExpanded(not dock.expanded())
            self.singleShot(2000, toogle)

        toogle()

        self.app.exec_()
コード例 #38
0
ファイル: test_dropshadow.py プロジェクト: 675801717/orange3
    def test(self):
        lv = QListView()
        mw = QMainWindow()
        # Add two tool bars, the shadow should extend over them.
        mw.addToolBar(Qt.BottomToolBarArea, QToolBar())
        mw.addToolBar(Qt.TopToolBarArea, QToolBar())
        mw.setCentralWidget(lv)

        f = dropshadow.DropShadowFrame(color=Qt.blue, radius=20)

        f.setWidget(lv)

        self.assertIs(f.parentWidget(), mw)
        self.assertIs(f.widget(), lv)

        mw.show()

        self.app.processEvents()

        self.singleShot(3000, lambda: f.setColor(Qt.red))
        self.singleShot(4000, lambda: f.setRadius(30))
        self.singleShot(5000, lambda: f.setRadius(40))
        self.app.exec_()
コード例 #39
0
ファイル: test_dropshadow.py プロジェクト: yisuax11/orange2
    def test(self):
        lv = QListView()
        mw = QMainWindow()
        # Add two tool bars, the shadow should extend over them.
        mw.addToolBar(Qt.BottomToolBarArea, QToolBar())
        mw.addToolBar(Qt.TopToolBarArea, QToolBar())
        mw.setCentralWidget(lv)

        f = dropshadow.DropShadowFrame(color=Qt.blue, radius=20)

        f.setWidget(lv)

        self.assertIs(f.parentWidget(), mw)
        self.assertIs(f.widget(), lv)

        mw.show()

        self.app.processEvents()

        self.singleShot(3000, lambda: f.setColor(Qt.red))
        self.singleShot(4000, lambda: f.setRadius(30))
        self.singleShot(5000, lambda: f.setRadius(40))
        self.app.exec_()
コード例 #40
0
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_()
コード例 #41
0
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_()
コード例 #42
0
 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
コード例 #43
0
ファイル: testBoxDecayView.py プロジェクト: Andrej-CMS/cmssw
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_()
コード例 #44
0
ファイル: testLineDecayView.py プロジェクト: Andrej-CMS/cmssw
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_()
コード例 #45
0
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_())
コード例 #46
0
    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_())
コード例 #47
0
def main():
    qapp = QApplication(sys.argv)
    window = QMainWindow()
    view = QWebView()
    window.setWindowTitle('MUTE - Collaborative Text Editor')

    def file_save():
        name = QFileDialog.getSaveFileName(window, 'Save File')
        if len(name.strip()) > 0:
            print('SAVE|' + name)
            sys.stdout.flush()

    def file_open():
        name = QFileDialog.getOpenFileName(window, 'Open File')
        if len(name.strip()) > 0:
            print('OPEN|' + name)
            sys.stdout.flush()

    def dir_open():
        dir_name = QFileDialog.getExistingDirectory(window, 'Open Directory',
                                                    'C:\\',
                                                    QFileDialog.ShowDirsOnly)
        if len(name.strip()) > 0:
            print('DIR|' + dir_name)
            sys.stdout.flush()

    def set_console():
        name = QFileDialog.getOpenFileName(window, 'Set Console')
        if len(name.strip()) > 0:
            print('SCONSOLE|' + name)
            sys.stdout.flush()

    extractAction = QAction("&Exit", window)
    extractAction.setStatusTip('Leave The App')
    extractAction.triggered.connect(sys.exit)

    extractAction2 = QAction("&Open File", window)
    extractAction2.setStatusTip('Open a file')
    extractAction2.triggered.connect(file_open)

    extractAction4 = QAction("&Save File", window)
    extractAction4.setStatusTip('Save a file')
    extractAction4.triggered.connect(file_save)

    extractAction5 = QAction("&Set Console", window)
    extractAction5.triggered.connect(set_console)

    extractAction3 = QAction("&Open Project Directory", window)
    extractAction3.setStatusTip('Open a directory')
    extractAction3.triggered.connect(dir_open)

    mainMenu = window.menuBar()
    fileMenu = mainMenu.addMenu('&File')
    fileMenu.addAction(extractAction)
    fileMenu.addAction(extractAction2)
    fileMenu.addAction(extractAction4)
    fileMenu.addAction(extractAction3)
    fileMenu.addAction(extractAction5)

    def set_bold():
        print('SET_BOLD|', end='\n', file=sys.stdout, flush=True)
        # sys.stdout.flush()
    def set_italics():
        print('SET_ITALICS|')
        sys.stdout.flush()

    def set_html_tag():
        text, ok = QInputDialog.getText(window, 'Text Input Dialog',
                                        'Enter HTML Tag:')
        if ok:
            textArray = text.strip().split()
            name = textArray[0]
            attributes = ' '.join(textArray[1:])
            print('SET_HTML_TAG|' + str(name) + '|' + attributes)
            sys.stdout.flush()

    boldAction = QAction("&Set Bold", window)
    boldAction.triggered.connect(set_bold)
    italicsAction = QAction("&Set Italics", window)
    italicsAction.triggered.connect(set_italics)
    htmlTagAction = QAction("&Set Html Tag", window)
    htmlTagAction.triggered.connect(set_html_tag)

    editMenu = mainMenu.addMenu('&Edit')
    editMenu.addAction(boldAction)
    editMenu.addAction(italicsAction)
    editMenu.addAction(htmlTagAction)

    view.load(QUrl('http://127.0.0.1:8000/index.html'))
    #view.page().mainFrame().evaluateJavaScript('var IS_ADMIN = true;')
    # view.setHtml('<h1>hi</h1>')
    window.setCentralWidget(view)
    window.showMaximized()
    view.show()
    qapp.exec_()
コード例 #48
0
        
        
    def update(self):
        self._processChangeSignals -= 1
        self.value.setMinimum(self.model.minimum.asUnit(str(self.unit.currentText())))
        self.value.setMaximum(self.model.maximum.asUnit(str(self.unit.currentText())))
        self.value.setValue(self.model.value.asUnit(str(self.unit.currentText())))
        self._processChangeSignals += 1
    def valueEntered(self):
        if self._processChangeSignals == 0:
            self.model.value = type(self.model.value)(self.value.value(),unit=str(self.unit.currentText()))
    


if __name__ == '__main__':
    import sys
    from PyQt4.QtGui import QApplication,QMainWindow
    from experiment import experiment
    from utility import quantities 
    
    application = QApplication(sys.argv)
    window = QMainWindow()
    
    widgetUnderTest = QuantityWidgetController(window)
    theModel = experiment.Property(quantities.Frequency(3e9,'Hz'))
    
    widgetUnderTest.model = theModel
    window.setCentralWidget(widgetUnderTest)
    window.show()
        
    sys.exit(application.exec_())
コード例 #49
0
ファイル: main_window.py プロジェクト: mcopik/PyGestures
class MainWindow(object):
    '''
    Main window in View.
    '''
    MAIN_WINDOW_TITLE = "PyGestures"
    def __init__(self):
        '''
        Constructor
        '''
        self.mainWindow = QMainWindow();
        self.mainWindow.setWindowTitle(self.MAIN_WINDOW_TITLE)
        self.mainWindowSignals = MainWindowSignals(self);
        self._createWidgets();
        self._connectSignals();
        self.mainWindow.setCentralWidget(self.mainWidget);
        self.mainWindow.show();
        
    def _createWidgets(self):
        '''
        '''
        self.mainWidget = QWidget(self.mainWindow)
        self.videoWidget = VideoWidget()
        self.scaleButton = QPushButton("Scale capture",self.mainWindow)
        self.trainNetworkButton = QPushButton("Train network",self.mainWindow)
        self.captureButton = QPushButton("Capture",self.mainWindow)
        self.classifyButton = QPushButton("Classify",self.mainWindow)
        self.layout = QGridLayout();
        self.layout.addWidget(self.videoWidget,0,0)
        self.layout.addWidget(self.scaleButton,1,0)
        self.mainWidget.setLayout(self.layout)
        self.cbMinSlider = QSlider(Qt.Horizontal, self.mainWindow)
        self.layout.addWidget(self.cbMinSlider,2,0)
        self.cbMaxSlider = QSlider(Qt.Horizontal, self.mainWindow)
        self.layout.addWidget(self.cbMaxSlider,3,0)
        self.crMinSlider = QSlider(Qt.Horizontal, self.mainWindow)
        self.layout.addWidget(self.crMinSlider,4,0)
        self.crMaxSlider = QSlider(Qt.Horizontal, self.mainWindow)
        self.layout.addWidget(self.crMaxSlider,5,0)
        self.layout.addWidget(self.captureButton,6,0)
        self.layout.addWidget(self.trainNetworkButton,7,0)
        self.layout.addWidget(self.classifyButton,8,0)
        #self.cbMinSlider.setFocusPolicy(QtCore.Qt.NoFocus)
        #self.cbMinSlider.setGeometry(30, 40, 100, 30)
        self.cbMinSlider.setValue(80)
        self.cbMinSlider.setRange(0,255)
        self.cbMinSlider.valueChanged[int].connect(self.mainWindowSignals.changedValueCbMin)
        self.cbMaxSlider.setRange(0,255)
        self.cbMaxSlider.setValue(135)
        self.cbMaxSlider.valueChanged[int].connect(self.mainWindowSignals.changedValueCbMax)
        self.crMinSlider.setRange(0,255)
        self.crMinSlider.setValue(130)
        self.crMinSlider.valueChanged[int].connect(self.mainWindowSignals.changedValueCrMin)
        self.crMaxSlider.setRange(0,255)
        self.crMaxSlider.setValue(180)
        self.crMaxSlider.valueChanged[int].connect(self.mainWindowSignals.changedValueCrMax)
    def _connectSignals(self):
        '''
        '''
        self.mainWindowSignals.camera = self.videoWidget._capture
        self.mainWindow.connect(self.scaleButton,SIGNAL("clicked()"),self.mainWindowSignals.prepareCapture)
        self.mainWindow.connect(self.captureButton,SIGNAL("clicked()"),self.mainWindowSignals.captureImage)
        self.mainWindow.connect(self.trainNetworkButton,SIGNAL("clicked()"),self.mainWindowSignals.trainNetwork)
        self.mainWindow.connect(self.classifyButton,SIGNAL("clicked()"),self.mainWindowSignals.captureImage)
コード例 #50
0
ファイル: 2669.py プロジェクト: jlg234bob/PPQT
 import sys
 from PyQt4.QtGui import (QApplication, QFileDialog, QMainWindow,
                          QPlainTextEdit, QTextCursor)
 from PyQt4.QtCore import (QFile, QTextStream, QString, QRegExp)
 app = QApplication(sys.argv)  # create the app
 import pqIMC
 IMC = pqIMC.tricorder()
 import pqMsgs
 pqMsgs.IMC = IMC
 IMC.fontFamily = QString(u"Courier")
 IMC.editWidget = QPlainTextEdit()
 IMC.pageTable = pagedb()
 widj = pagesPanel()
 MW = QMainWindow()
 IMC.mainWindow = MW
 MW.setCentralWidget(widj)
 MW.setWinModStatus = setWinModStatus
 MW.show()
 fn = QFileDialog.getOpenFileName(None, "Select a Test Book")
 print(fn)
 fh = QFile(fn)
 if not fh.open(QFile.ReadOnly):
     raise IOError, unicode(fh.errorString())
 stream = QTextStream(fh)
 stream.setCodec("UTF-8")
 IMC.editWidget.setPlainText(stream.readAll())  # load the editor doc
 widj.docWillChange()
 # Code from pqEdit to parse a doc by lines and extract page seps.
 reLineSep = QRegExp(
     u'-----File: ([^\\.]+)\\.png---((\\\\[^\\\\]*)+)\\\\-*',
     Qt.CaseSensitive)
コード例 #51
0
    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_()
コード例 #52
0
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()
コード例 #53
0
ファイル: test_completion.py プロジェクト: vi/qutepart
class Test(unittest.TestCase):
    """Base class for tests
    """
    app = base.papp  # app crashes, if created more than once

    def setUp(self):
        self._window = QMainWindow()
        self.qpart = Qutepart()
        self._window.setCentralWidget(self.qpart)
        self._window.menuBar().addAction(self.qpart.invokeCompletionAction)

    def tearDown(self):
        del self.qpart

    def test_down_selects_first(self):
        self.qpart.text = 'aaaa\nbbbb\ncccX\ndddd\ncccY'

        while self.app.hasPendingEvents():
            self.app.processEvents()

        QTest.keyClicks(self.qpart, "ccc")
        QTest.keyClick(self.qpart, Qt.Key_Down)
        QTest.keyClick(self.qpart, Qt.Key_Enter)
        QTest.keyClick(self.qpart, Qt.Key_Enter)
        self.assertEqual(self.qpart.text, 'cccX\naaaa\nbbbb\ncccX\ndddd\ncccY')

    def test_down_selects_second(self):
        self.qpart.text = 'aaaa\nbbbb\ncccX\ndddd\ncccY'

        base._processPendingEvents(self.app)

        QTest.keyClicks(self.qpart, "ccc")

        QTest.keyClick(self.qpart, Qt.Key_Down)
        QTest.keyClick(self.qpart, Qt.Key_Down)
        QTest.keyClick(self.qpart, Qt.Key_Enter)
        QTest.keyClick(self.qpart, Qt.Key_Enter)
        self.assertEqual(self.qpart.text, 'cccY\naaaa\nbbbb\ncccX\ndddd\ncccY')

    @unittest.skip("Crashes Qt 4.8.3")
    def test_click_selects_first(self):
        self.qpart.text = 'aaaa\nbbbb\ncccX\ndddd\ncccY'

        QTest.keyClicks(self.qpart, "ccc")
        QTest.mouseClick(self.qpart, Qt.LeftButton)
        QTest.keyClick(self.qpart, Qt.Key_Enter)
        self.assertEqual(self.qpart.text, 'cccY\naaaa\nbbbb\ncccX\ndddd\ncccY')

    def test_tab_completes(self):
        self.qpart.text = 'aaaaa\naaaaaXXXXX\n'

        base._processPendingEvents(self.app)

        self.qpart.cursorPosition = (2, 0)
        QTest.keyClicks(self.qpart, "aaa")
        QTest.keyClick(self.qpart, Qt.Key_Tab)
        self.assertEqual(self.qpart.text, 'aaaaa\naaaaaXXXXX\naaaaa')
        QTest.keyClick(self.qpart, Qt.Key_Tab)
        self.assertEqual(self.qpart.text, 'aaaaa\naaaaaXXXXX\naaaaaXXXXX')

    def test_manual(self):
        self._window.show()

        self.qpart.text = 'aaaaa\naaaaaXXXXX\n'

        base._processPendingEvents(self.app)

        self.qpart.cursorPosition = (2, 0)
        QTest.keyClicks(self.qpart, "a")

        QTest.keyPress(self.qpart, Qt.Key_Space, Qt.ControlModifier, 100)

        QTest.keyClicks(self.qpart, "a")
        QTest.keyClick(self.qpart, Qt.Key_Tab)
        self.assertEqual(self.qpart.text, 'aaaaa\naaaaaXXXXX\naaaaa')

    @base.in_main_loop
    def test_too_long_list(self):
        self._window.show()

        self.qpart.text = '\n'.join(['asdf' + str(i) \
                                        for i in range(100)]) + '\n'
        base._processPendingEvents(self.app)
        self.qpart.cursorPosition = (100, 0)
        QTest.keyClicks(self.qpart, "asdf")
        self.assertIsNotNone(self.qpart._completer._widget)

        self.qpart.text = '\n'.join(['asdf' + str(i) \
                                        for i in range(1000)]) + '\n'
        base._processPendingEvents(self.app)
        self.qpart.cursorPosition = (1000, 0)
        QTest.keyClicks(self.qpart, "asdf")
        self.assertIsNone(self.qpart._completer._widget)

        QTest.keyPress(self.qpart, Qt.Key_Space, Qt.ControlModifier, 100)
        self.assertIsNotNone(self.qpart._completer._widget)
コード例 #54
0
    def __init__(self, parent, numWin):
        def setTreeView():
            def setModel():
                self.model = QgsLayerTreeModel(ltg)
                self.model.setFlag(QgsLayerTreeModel.AllowNodeReorder)
                self.model.setFlag(QgsLayerTreeModel.AllowNodeChangeVisibility,
                                   True)
                self.tview.setModel(self.model)

            self.tview = QgsLayerTreeView(self)
            self.tview.setSelectionMode(QAbstractItemView.ExtendedSelection)
            setModel()
            self.tview.currentLayerChanged.connect(
                self.currentLayerChanged.emit)

        def setupUi():
            self.setAllowedAreas(Qt.LeftDockWidgetArea)
            winLegend.setWindowFlags(Qt.Widget)
            toolBar.setFloatable(False)
            toolBar.setMovable(False)
            winLegend.addToolBar(toolBar)
            self.setWidget(winLegend)

        def addActions():
            actn = QAction(winLegend)
            actn.setIcon(qgis.utils.iface.actionShowSelectedLayers().icon())
            actn.setIconText('Show selected layers')
            actn.setObjectName('showLayer')
            actn.triggered.connect(self.onAction)
            toolBar.addAction(actn)

            actn = QAction(winLegend)
            actn.setIcon(qgis.utils.iface.actionHideSelectedLayers().icon())
            actn.setIconText('Hide selected layers')
            actn.setObjectName('hideLayer')
            actn.triggered.connect(self.onAction)
            toolBar.addAction(actn)

            actn = QAction(winLegend)
            actn.setIcon(qgis.utils.iface.actionRemoveLayer().icon())
            actn.setIconText('Remove selected layers')
            actn.setObjectName('removeLayer')
            actn.triggered.connect(self.onAction)
            toolBar.addAction(actn)

            toolBar.addSeparator()

            actn = QAction(winLegend)
            actn.setIcon(qgis.utils.iface.actionDuplicateLayer().icon())
            actn.setIconText('Add selected layers from main map')
            actn.setObjectName('addLayer')
            actn.triggered.connect(self.onAction)
            toolBar.addAction(actn)

            actn = QAction(winLegend)
            actn.setIcon(
                QIcon(
                    os.path.join(os.path.dirname(__file__),
                                 'mActionCurrentLayer.png')))
            actn.setIconText('Current layer for main map')
            actn.setObjectName('currentLayer')
            actn.triggered.connect(self.onAction)
            toolBar.addAction(actn)

            actn = QAction(winLegend)
            actn.setIcon(
                QIcon(
                    os.path.join(os.path.dirname(__file__),
                                 'mActionAddGroup.png')))
            actn.setObjectName('syncGroup')
            actn.triggered.connect(self.onAction)
            toolBar.addAction(actn)

        super(AuxiliaryLegend, self).__init__("#%d - Layers" % numWin, parent)

        ltg = parent.ltg
        self.tview = self.model = self.bridge = None
        self.textSync = "Sync with group(main map) for new layers"
        self.actSync = None
        setTreeView()

        winLegend = QMainWindow(self)
        toolBar = QToolBar(winLegend)
        setupUi()
        addActions()
        self.addNameSyncGroup("None")
        winLegend.setCentralWidget(self.tview)
コード例 #55
0
def main(icon_spec):
    app = QApplication(sys.argv)

    main_window = QMainWindow()

    def sigint_handler(*args):
        main_window.close()

    signal.signal(signal.SIGINT, sigint_handler)
    # the timer enables triggering the sigint_handler
    signal_timer = QTimer()
    signal_timer.start(100)
    signal_timer.timeout.connect(lambda: None)

    tool_bar = QToolBar()
    main_window.addToolBar(Qt.TopToolBarArea, tool_bar)

    table_view = QTableView()
    table_view.setSelectionBehavior(QAbstractItemView.SelectRows)
    table_view.setSelectionMode(QAbstractItemView.SingleSelection)
    table_view.setSortingEnabled(True)
    main_window.setCentralWidget(table_view)

    proxy_model = QSortFilterProxyModel()
    proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
    proxy_model.setFilterKeyColumn(1)
    table_view.setModel(proxy_model)
    proxy_model.layoutChanged.connect(table_view.resizeRowsToContents)

    item_model = QStandardItemModel()
    proxy_model.setSourceModel(item_model)

    # get all icons and their available sizes
    QIcon.setThemeName("gnome")
    icons = []
    all_sizes = set([])
    for context, icon_names in icon_spec:
        for icon_name in icon_names:
            icon = QIcon.fromTheme(icon_name)
            sizes = []
            for size in icon.availableSizes():
                size = (size.width(), size.height())
                sizes.append(size)
                all_sizes.add(size)
            sizes.sort()
            icons.append({
                'context': context,
                'icon_name': icon_name,
                'icon': icon,
                'sizes': sizes,
            })
    all_sizes = list(all_sizes)
    all_sizes.sort()

    # input field for filter
    def filter_changed(value):
        proxy_model.setFilterRegExp(value)
        table_view.resizeRowsToContents()

    filter_line_edit = QLineEdit()
    filter_line_edit.setMaximumWidth(200)
    filter_line_edit.setPlaceholderText('Filter name')
    filter_line_edit.setToolTip(
        'Filter name optionally using regular expressions (' +
        QKeySequence(QKeySequence.Find).toString() + ')')
    filter_line_edit.textChanged.connect(filter_changed)
    tool_bar.addWidget(filter_line_edit)

    # actions to toggle visibility of available sizes/columns
    def action_toggled(index):
        column = 2 + index
        table_view.setColumnHidden(column,
                                   not table_view.isColumnHidden(column))
        table_view.resizeColumnsToContents()
        table_view.resizeRowsToContents()

    signal_mapper = QSignalMapper()
    for i, size in enumerate(all_sizes):
        action = QAction('%dx%d' % size, tool_bar)
        action.setCheckable(True)
        action.setChecked(True)
        tool_bar.addAction(action)
        action.toggled.connect(signal_mapper.map)
        signal_mapper.setMapping(action, i)
        # set tool tip and handle key sequence
        tool_tip = 'Toggle visibility of column'
        if i < 10:
            digit = ('%d' % (i + 1))[-1]
            tool_tip += ' (%s)' % QKeySequence('Ctrl+%s' % digit).toString()
        action.setToolTip(tool_tip)
    signal_mapper.mapped.connect(action_toggled)

    # label columns
    header_labels = ['context', 'name']
    for width, height in all_sizes:
        header_labels.append('%dx%d' % (width, height))
    item_model.setColumnCount(len(header_labels))
    item_model.setHorizontalHeaderLabels(header_labels)

    # fill rows
    item_model.setRowCount(len(icons))
    for row, icon_data in enumerate(icons):
        # context
        item = QStandardItem(icon_data['context'])
        item.setFlags(item.flags() ^ Qt.ItemIsEditable)
        item_model.setItem(row, 0, item)
        # icon name
        item = QStandardItem(icon_data['icon_name'])
        item.setFlags(item.flags() ^ Qt.ItemIsEditable)
        item_model.setItem(row, 1, item)
        for index_in_all_sizes, size in enumerate(all_sizes):
            column = 2 + index_in_all_sizes
            if size in icon_data['sizes']:
                # icon as pixmap to keep specific size
                item = QStandardItem('')
                pixmap = icon_data['icon'].pixmap(size[0], size[1])
                item.setData(pixmap, Qt.DecorationRole)
                item.setFlags(item.flags() ^ Qt.ItemIsEditable)
                item_model.setItem(row, column, item)
            else:
                # single space to be sortable against icons
                item = QStandardItem(' ')
                item.setFlags(item.flags() ^ Qt.ItemIsEditable)
                item_model.setItem(row, column, item)

    table_view.resizeColumnsToContents()
    # manually set row heights because resizeRowsToContents is not working properly
    for row, icon_data in enumerate(icons):
        if len(icon_data['sizes']) > 0:
            max_size = icon_data['sizes'][-1]
            table_view.setRowHeight(row, max_size[1])

    # enable focus find (ctrl+f) and toggle columns (ctrl+NUM)
    def main_window_keyPressEvent(self,
                                  event,
                                  old_keyPressEvent=QMainWindow.keyPressEvent):
        if event.matches(QKeySequence.Find):
            filter_line_edit.setFocus()
            return
        if event.modifiers() == Qt.ControlModifier and event.key(
        ) >= Qt.Key_0 and event.key() <= Qt.Key_9:
            index = event.key() - Qt.Key_1
            if event.key() == Qt.Key_0:
                index += 10
            action = signal_mapper.mapping(index)
            if action:
                action.toggle()
                return
        old_keyPressEvent(self, event)

    main_window.keyPressEvent = new.instancemethod(main_window_keyPressEvent,
                                                   table_view, None)

    # enable copy (ctrl+c) name of icon to clipboard
    def table_view_keyPressEvent(self,
                                 event,
                                 old_keyPressEvent=QTableView.keyPressEvent):
        if event.matches(QKeySequence.Copy):
            selection_model = self.selectionModel()
            if selection_model.hasSelection():
                index = selection_model.selectedRows()[0]
                source_index = self.model().mapToSource(index)
                item = self.model().sourceModel().item(source_index.row(), 1)
                icon_name = item.data(Qt.EditRole)
                app.clipboard().setText(icon_name.toString())
                return
        old_keyPressEvent(self, event)

    table_view.keyPressEvent = new.instancemethod(table_view_keyPressEvent,
                                                  table_view, None)
    print 'Icon Theme: ', QIcon.themeName()

    print 'Theme Search Paths:'
    for item in QIcon.themeSearchPaths():
        print item
    main_window.showMaximized()
    return app.exec_()
コード例 #56
0
        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_())
コード例 #57
0
ファイル: pqChars.py プロジェクト: jlg234bob/PPQT

if __name__ == "__main__":
    import sys
    from PyQt4.QtCore import (Qt, QFile, QIODevice, QTextStream)
    from PyQt4.QtGui import (QApplication, QFileDialog, QMainWindow)
    import pqIMC
    IMC = pqIMC.tricorder()  # create inter-module communicator
    app = QApplication(sys.argv)  # create an app
    import pqMsgs
    pqMsgs.IMC = IMC
    import pqLists
    IMC.charCensus = pqLists.vocabList()
    CP = charsPanel()  # create the widget with the table view and model
    MW = QMainWindow()
    MW.setCentralWidget(CP)
    IMC.statusBar = MW.statusBar()
    MW.show()
    utname = QFileDialog.getOpenFileName(MW, "UNIT TEST DATA FOR CHARS", ".")
    utfile = QFile(utname)
    if not utfile.open(QIODevice.ReadOnly):
        raise IOError, unicode(utfile.errorString())

    CP.docWillChange()

    utstream = QTextStream(utfile)
    utstream.setCodec("UTF-8")
    utqs = utstream.readAll()
    for i in range(utqs.count()):
        qc = utqs.at(i)
        cat = qc.category()