def keyReleaseEvent(self, event): super(myCodeWidget, self).keyReleaseEvent(event) # self.setMouseTracking(False) QApplication.restoreOverrideCursor() if self.popup: self.popup.close() self.popup = None
def setUp(self): qt_app = QApplication.instance() if qt_app is None: qt_app = QApplication([]) self.qt_app = qt_app self.gui = GUI() self.event_loop_helper = EventLoopHelper(qt_app=self.qt_app, gui=self.gui) try: import traitsui.api except ImportError: self.traitsui_raise_patch = None else: self.traitsui_raise_patch = mock.patch( "traitsui.qt4.ui_base._StickyDialog.raise_") self.traitsui_raise_patch.start() def new_activate(self): self.control.activateWindow() self.pyface_raise_patch = mock.patch( "pyface.ui.qt4.window.Window.activate", new_callable=lambda: new_activate, ) self.pyface_raise_patch.start()
def test_selection_listener_disconnected(self): """Check that selection listeners get correctly disconnected""" from pyface.qt.QtGui import QApplication, QItemSelectionModel from pyface.ui.qt4.util.testing import event_loop obj = ListStrEditorWithSelectedIndex(values=["value1", "value2"]) with reraise_exceptions(): qt_app = QApplication.instance() if qt_app is None: qt_app = QApplication([]) # open the UI and run until the dialog is closed with create_ui(obj, dict(view=single_select_item_view)) as ui: pass # now run again and change the selection with create_ui( obj, dict(view=single_select_item_view) ) as ui, event_loop(): editor = ui.get_editors("values")[0] list_view = editor.list_view mi = editor.model.index(1) list_view.selectionModel().select( mi, QItemSelectionModel.SelectionFlag.ClearAndSelect ) obj.selected = "value2"
def test_selection_listener_disconnected(): """ Check that selection listeners get correctly disconnected """ from pyface.api import GUI from pyface.qt.QtGui import QApplication, QItemSelectionModel from pyface.ui.qt4.util.event_loop_helper import EventLoopHelper from pyface.ui.qt4.util.testing import event_loop obj = ListStrEditorWithSelectedIndex(values=['value1', 'value2']) with store_exceptions_on_all_threads(): qt_app = QApplication.instance() if qt_app is None: qt_app = QApplication([]) helper = EventLoopHelper(gui=GUI(), qt_app=qt_app) # open the UI and run until the dialog is closed ui = obj.edit_traits(view=single_select_item_view) with helper.delete_widget(ui.control): press_ok_button(ui) # now run again and change the selection ui = obj.edit_traits(view=single_select_item_view) with event_loop(): editor = ui.get_editors('values')[0] list_view = editor.list_view mi = editor.model.index(1) list_view.selectionModel().select( mi, QItemSelectionModel.ClearAndSelect) obj.selected = 'value2'
def init(self): """ Prepare the event loop for use. """ qt_app = QApplication.instance() if qt_app is None: qt_app = QApplication([]) self.qt_app = qt_app self._attribute_setter = AttributeSetter() self._attribute_setter.setattr.connect( self._attribute_setter._on_setattr, Qt.QueuedConnection)
def setUp(self): from pyface.qt.QtGui import QApplication from pyface.ui.qt4.util.event_loop_helper import EventLoopHelper qt_app = QApplication.instance() if qt_app is None: qt_app = QApplication([]) self.qt_app = qt_app if NativeScrollBar is None: raise unittest.SkipTest("Qt4 NativeScrollbar not available.") self.gui = GUI() self.event_loop_helper = EventLoopHelper(gui=self.gui, qt_app=qt_app) self.container = Container(position=[0, 0], bounds=[600, 600]) self.window = Window(None, size=(600, 600), component=self.container)
def mouseMoveEvent(self, event): if QLineF(event.screenPos(), event.buttonDownScreenPos(Qt.LeftButton)).length() < QApplication.startDragDistance(): return print "AtomItem::mouseMoveEvent" drag = QDrag(event.widget()) mime = QMimeData() # A weak solution that could not be implemented in # C++ mime.atom = self.atom mime.atom_item = self drag.setMimeData(mime) mime.setText("Atom") pixmap = QPixmap(int(self.boundingRect().width()), int(self.boundingRect().height())) pixmap.fill(Qt.white) painter = QPainter(pixmap) painter.setRenderHint(QPainter.Antialiasing) self.paint(painter, QStyleOptionGraphicsItem(), event.widget()) painter.end() pixmap.setMask(pixmap.createHeuristicMask()) drag.setPixmap(pixmap) drag.setHotSpot(QPoint(int(self.boundingRect().width()/2.0), int(self.boundingRect().height()/2.0))) drag.exec_() self.setCursor(Qt.OpenHandCursor)
def mouseMoveEvent(self, event): if QLineF(event.screenPos(), event.buttonDownScreenPos(Qt.LeftButton)).length() < QApplication.startDragDistance(): return drag = QDrag(event.widget()) mime = QMimeData() drag.setMimeData(mime) mime.setText("ExpressionBasedForce") pixmap = QPixmap(int(self.boundingRect().width()), int(self.boundingRect().height())) pixmap.fill(Qt.white) painter = QPainter(pixmap) painter.setRenderHint(QPainter.Antialiasing) self.paint(painter, QStyleOptionGraphicsItem(), event.widget()) painter.end() pixmap.setMask(pixmap.createHeuristicMask()) drag.setPixmap(pixmap) drag.setHotSpot(QPoint(int(self.boundingRect().width()/2.0), int(self.boundingRect().height()/2.0))) drag.exec_() self.setCursor(Qt.OpenHandCursor)
def test_selection_listener_disconnected(): """ Check that selection listeners get correctly disconnected """ from pyface.api import GUI from pyface.qt.QtGui import QApplication, QItemSelectionModel from pyface.ui.qt4.util.event_loop_helper import EventLoopHelper from pyface.ui.qt4.util.testing import event_loop obj = ListStrEditorWithSelectedIndex(values=['value1', 'value2']) with store_exceptions_on_all_threads(): qt_app = QApplication.instance() if qt_app is None: qt_app = QApplication([]) helper = EventLoopHelper(gui=GUI(), qt_app=qt_app) # open the UI and run until the dialog is closed ui = obj.edit_traits(view=single_select_item_view) with helper.delete_widget(ui.control): press_ok_button(ui) # now run again and change the selection ui = obj.edit_traits(view=single_select_item_view) with event_loop(): editor = ui.get_editors('values')[0] list_view = editor.list_view mi = editor.model.index(1) list_view.selectionModel().select(mi, QItemSelectionModel.ClearAndSelect) obj.selected = 'value2'
def setUp(self): qt_app = QApplication.instance() if qt_app is None: qt_app = QApplication([]) self.qt_app = qt_app self.gui = GUI() self.event_loop_helper = EventLoopHelper( qt_app=self.qt_app, gui=self.gui ) try: import traitsui.api except ImportError: self.traitsui_raise_patch = None else: self.traitsui_raise_patch = mock.patch( 'traitsui.qt4.ui_base._StickyDialog.raise_') self.traitsui_raise_patch.start() def new_activate(self): self.control.activateWindow() self.pyface_raise_patch = mock.patch( 'pyface.ui.qt4.window.Window.activate', new_callable=lambda: new_activate) self.pyface_raise_patch.start()
def _paste(self): clipboard = QApplication.clipboard() md = clipboard.mimeData() items = md.instance() if items is not None: editor = self._editor model = editor.model insert_mode = 'after' selection = self.selectedIndexes() if len(selection): offset = 1 if insert_mode == 'after' else 0 idx = selection[-1].row() + offset else: idx = len(editor.value) if self._cut_indices: if not any((ci <= idx for ci in self._cut_indices)): idx += len(self._cut_indices) model = editor.model for ci in self._cut_indices: model.removeRow(ci) self._cut_indices = None # paste_func = self.paste_func # if paste_func is None: # paste_func = lambda x: x.clone_traits() for ri, ci in reversed(items): model.insertRow(idx, obj=ci)
def start(): # app = QApplication(sys.argv) # Don't create a new QApplication, it would unhook the Events # set by Traits on the existing QApplication. Simply use the # '.instance()' method to retrieve the existing one. app = QApplication.instance() window = MainWindow() sys.exit(app.exec_())
def get_display_size(): size = namedtuple('Size', 'width height') from pyface.qt.QtGui import QApplication desktop = QApplication.desktop() rect = desktop.screenGeometry() w, h = rect.width(), rect.height() return size(w, h)
def setUp(self): qt_app = QApplication.instance() if qt_app is None: qt_app = QApplication([]) self.qt_app = qt_app self.gui = GUI() self.event_loop_helper = EventLoopHelper(qt_app=self.qt_app, gui=self.gui) self.traitsui_raise_patch = mock.patch( 'traitsui.qt4.ui_base._StickyDialog.raise_') self.traitsui_raise_patch.start() def new_activate(self): self.control.activateWindow() self.pyface_raise_patch = mock.patch( 'pyface.ui.qt4.window.Window.activate', new_callable=lambda: new_activate) self.pyface_raise_patch.start()
def test_create_traitsfont(self): expected_outcomes = {} expected_outcomes[""] = TraitsFont() for weight, qt_weight in font_weights.items(): expected_outcomes[weight] = TraitsFont() expected_outcomes[weight].setWeight(qt_weight) for style, qt_style in font_styles.items(): expected_outcomes[style] = TraitsFont() expected_outcomes[style].setStyle(qt_style) expected_outcomes["underline"] = TraitsFont() expected_outcomes["underline"].setUnderline(True) expected_outcomes["18"] = TraitsFont() expected_outcomes["18"].setPointSize(18) expected_outcomes["18 pt"] = TraitsFont() expected_outcomes["18 pt"].setPointSize(18) expected_outcomes["18 point"] = TraitsFont() expected_outcomes["18 point"].setPointSize(18) for family, qt_style_hint in font_families.items(): expected_outcomes[family] = TraitsFont() expected_outcomes[family].setStyleHint(qt_style_hint) default_size = QApplication.font().pointSize() expected_outcomes["Courier"] = TraitsFont("Courier", default_size) expected_outcomes["Comic Sans"] = TraitsFont("Comic Sans", default_size) expected_outcomes[ "18 pt Bold Oblique Underline Comic Sans script"] = TraitsFont( "Comic Sans", 18, QFont.Weight.Bold, False) expected_outcomes[ "18 pt Bold Oblique Underline Comic Sans script"].setStyleHint( QFont.StyleHint.Cursive) expected_outcomes[ "18 pt Bold Oblique Underline Comic Sans script"].setStyle( QFont.Style.StyleOblique) expected_outcomes[ "18 pt Bold Oblique Underline Comic Sans script"].setUnderline( True) for name, expected in expected_outcomes.items(): with self.subTest(name=name): result = create_traitsfont(name) # test we get expected font self.assertIsInstance(result, TraitsFont) self.assert_qfont_equal(result, expected) # round-trip through font_to_str result_2 = create_traitsfont(font_to_str(result)) self.assert_qfont_equal(result, result_2)
def _copy(self): rows = sorted({ri.row() for ri in self.selectedIndexes()}) copy_object = [(ri, self._editor.value[ri].tocopy()) for ri in rows] # copy_object = [ri.row(), self._editor.value[ri.row()]) for ri in self.selectedIndexes()] mt = self._editor.factory.mime_type try: pdata = dumps(copy_object) except BaseException as e: print('tabular editor copy failed') self._editor.value[rows[0]].tocopy(verbose=True) return qmd = PyMimeData() qmd.MIME_TYPE = mt qmd.setData(six.text_type(mt), dumps(copy_object.__class__) + pdata) clipboard = QApplication.clipboard() clipboard.setMimeData(qmd)
def _paste(self): clipboard = QApplication.clipboard() md = clipboard.mimeData() try: items = md.instance() except AttributeError: return if items is not None: editor = self._editor model = editor.model insert_mode = 'after' selection = self.selectedIndexes() if len(selection): offset = 1 if insert_mode == 'after' else 0 idx = selection[-1].row() + offset else: idx = len(editor.value) if self._cut_indices: if not any((ci <= idx for ci in self._cut_indices)): idx += len(self._cut_indices) model = editor.model for ci in self._cut_indices: model.removeRow(ci) self._cut_indices = None # paste_func = self.paste_func # if paste_func is None: # paste_func = lambda x: x.clone_traits() for ri, ci in reversed(items): model.insertRow(idx, obj=ci)
def _translate(context, text, disambig): return QApplication.translate(context, text, disambig)
def clear_selected(self): # self.setMouseTracking(False) self.clear_underline() QApplication.restoreOverrideCursor()
# # Classes # class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.mayavi_widget = MayaviQWidget() # Layouting main_layout = QGridLayout() main_layout.addWidget(self.mayavi_widget, 1, 1) self.setCentralWidget(QWidget()) self.centralWidget().setLayout(main_layout) if __name__ == "__main__": # Don't create a new QApplication, it would unhook the Events # set by Traits on the existing QApplication. Simply use the # '.instance()' method to retrieve the existing one. app = QApplication.instance() main_window = MainWindow() main_window.show() # Start the main event loop. sys.exit(app.exec_())
""" This method compiles Universe. It is not possible to evaluate Universe along the time without compilation. """ print "compile" def run(self): """ This methods start procedure of evaluation of universe along the time. """ print "run" def abort(self): """ This method resets positions of matters and number of atoms to initial state, which is saved right before evaluation started. """ print "abort" if __name__ == "__main__": # Don't create a new QApplication, it would unhook the Events # set by Traits on the existing QApplication. Simply use the # '.instance()' method to retrieve the existing one. app = QApplication(sys.argv) universe_widget = UniverseWidget() universe_widget.show() # Start the main event loop. sys.exit(app.exec_())
def keyPressEvent(self, event): super(myCodeWidget, self).keyPressEvent(event) if event.modifiers() & Qt.ControlModifier: QApplication.setOverrideCursor(QCursor(Qt.PointingHandCursor))
class _TableView(TableView): """ for drag and drop reference see https://github.com/enthought/traitsui/blob/master/traitsui/qt4/tree_editor.py """ paste_func = None drop_factory = None # link_copyable = True copyable = True # _copy_cache = None # _linked_copy_cache = None _dragging = None _cut_indices = None option_select = False drag_enabled = True def __init__(self, editor, layout=None, *args, **kw): super(_TableView, self).__init__(editor, *args, **kw) # self.setItemDelegate(ItemDelegate(self)) # self.setup_consumer(main=True) editor = self._editor # # reimplement row height vheader = self.verticalHeader() # size = vheader.minimumSectionSize() height = None font = editor.adapter.get_font(editor.object, editor.name, 0) if font is not None: fnt = QtGui.QFont(font) size = QtGui.QFontMetrics(fnt) height = size.height() + 6 vheader.setFont(fnt) hheader = self.horizontalHeader() hheader.setFont(fnt) if editor.factory.row_height: height = editor.factory.row_height if height: vheader.setDefaultSectionSize(height) else: vheader.ResizeMode(QHeaderView.ResizeToContents) def set_bg_color(self, bgcolor): if isinstance(bgcolor, tuple): if len(bgcolor) == 3: bgcolor = 'rgb({},{},{})'.format(*bgcolor) elif len(bgcolor) == 4: bgcolor = 'rgba({},{},{},{})'.format(*bgcolor) elif isinstance(bgcolor, QColor): bgcolor = 'rgba({},{},{},{})'.format(bgcolor.red(), bgcolor.green(), bgcolor.blue(), bgcolor.alpha()) self.setStyleSheet('QTableView {{background-color: {}}}'.format(bgcolor)) def set_vertical_header_font(self, fnt): fnt = QtGui.QFont(fnt) vheader = self.verticalHeader() vheader.setFont(fnt) size = QtGui.QFontMetrics(fnt) vheader.setDefaultSectionSize(size.height() + 6) def set_horizontal_header_font(self, fnt): fnt = QtGui.QFont(fnt) vheader = self.horizontalHeader() vheader.setFont(fnt) def set_drag_enabled(self, d): if d: self.setDragDropMode(QtGui.QAbstractItemView.DragDrop) self.setDragEnabled(True) def startDrag(self, actions): if self._editor.factory.drag_external: idxs = self.selectedIndexes() rows = sorted(list(set([idx.row() for idx in idxs]))) drag_object = [(ri, self._editor.value[ri]) for ri in rows] md = PyMimeData.coerce(drag_object) self._dragging = self.currentIndex() drag = QtGui.QDrag(self) drag.setMimeData(md) drag.exec_(actions) else: super(_TableView, self).startDrag(actions) def dragEnterEvent(self, e): if self.is_external(): # Assume the drag is invalid. e.ignore() # Check what is being dragged. ed = e.mimeData() md = PyMimeData.coerce(ed) if md is None: return else: try: if not hasattr(ed.instance(), '__iter__'): return except AttributeError: return # We might be able to handle it (but it depends on what the final # target is). e.acceptProposedAction() else: super(_TableView, self).dragEnterEvent(e) def dragMoveEvent(self, e): if self.is_external(): e.acceptProposedAction() else: super(_TableView, self).dragMoveEvent(e) def dropEvent(self, e): if self.is_external(): data = PyMimeData.coerce(e.mimeData()).instance() if not hasattr(data, '__iter__'): return df = self.drop_factory if not df: df = lambda x: x row = self.rowAt(e.pos().y()) n = len(self._editor.value) if row == -1: row = n model = self._editor.model if self._dragging: rows = [ri for ri, _ in data] model.moveRows(rows, row) else: data = [di for _, di in data] with no_update(self._editor.object): for i, di in enumerate(reversed(data)): if isinstance(di, tuple): di = di[1] model.insertRow(row=row, obj=df(di)) for i, di in enumerate(reversed(df(data))): model.insertRow(row=row, obj=di) e.accept() self._dragging = None else: super(_TableView, self).dropEvent(e) def is_external(self): # print 'is_external', self._editor.factory.drag_external and not self._dragging return self._editor.factory.drag_external # and not self._dragging def keyPressEvent(self, event): if event.matches(QtGui.QKeySequence.Copy): # self._copy_cache = [self._editor.value[ci.row()] for ci in # self.selectionModel().selectedRows()] # self._copy_cache = self._get_selection() # self._editor.copy_cache = self._copy_cache self._cut_indices = None # add the selected rows to the clipboard self._copy() elif event.matches(QtGui.QKeySequence.Cut): self._cut_indices = [ci.row() for ci in self.selectionModel().selectedRows()] # self._copy_cache = [self._editor.value[ci] for ci in self._cut_indices] # self._copy_cache = self._get_selection(self._cut_indices) # self._editor.copy_cache = self._copy_cache elif event.matches(QtGui.QKeySequence.Paste): if self.pastable: self._paste() else: self._editor.key_pressed = TabularKeyEvent(event) self._key_press_hook(event) # private def _copy(self): rows = sorted({ri.row() for ri in self.selectedIndexes()}) copy_object = [(ri, self._editor.value[ri].tocopy()) for ri in rows] # copy_object = [ri.row(), self._editor.value[ri.row()]) for ri in self.selectedIndexes()] mt = self._editor.factory.mime_type try: pdata = dumps(copy_object) except BaseException, e: print 'tabular editor copy failed' self._editor.value[rows[0]].tocopy(verbose=True) return qmd = PyMimeData() qmd.MIME_TYPE = mt qmd.setData(unicode(mt), dumps(copy_object.__class__) + pdata) clipboard = QApplication.clipboard() clipboard.setMimeData(qmd)