def delete_widget(self, widget, timeout=1.0): """Runs the real Qt event loop until the widget provided has been deleted. Raises ConditionTimeoutError on timeout. Parameters ---------- widget : QObject The widget whose deletion will stop the event loop. timeout : float Number of seconds to run the event loop in the case that the widget is not deleted. Notes ----- `timeout` is rounded to the nearest millisecond. """ timer = QtCore.QTimer() timer.setSingleShot(True) timer.setInterval(round(timeout * 1000)) timer.timeout.connect(self.qt_app.quit) widget.destroyed.connect(self.qt_app.quit) yield timer.start() self.qt_app.exec_() if not timer.isActive(): # We exited the event loop on timeout raise ConditionTimeoutError( "Could not destroy widget before timeout: {!r}".format(widget))
def __init__(self): super(RobPathUI, self).__init__() path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) uic.loadUi(os.path.join(path, 'resources', 'robpath.ui'), self) self.plot = QMayavi() self.boxPlot.addWidget(self.plot) self.plot.drawWorkingArea() self.btnLoadMesh.clicked.connect(self.btnLoadMeshClicked) self.btnProcessMesh.clicked.connect(self.btnProcessMeshClicked) self.btnSaveRapid.clicked.connect(self.btnSaveRapidClicked) self.sbPositionX.valueChanged.connect(self.changePosition) self.sbPositionY.valueChanged.connect(self.changePosition) self.sbPositionZ.valueChanged.connect(self.changePosition) self.sbSizeX.valueChanged.connect(self.changeSize) self.sbSizeY.valueChanged.connect(self.changeSize) self.sbSizeZ.valueChanged.connect(self.changeSize) self.btnQuit.clicked.connect(self.btnQuitClicked) self.processing = False self.timer = QtCore.QTimer(self.plot) self.timer.timeout.connect(self.updateProcess) self.robpath = RobPath()
def test_set_trait_later_runs_later(self): # Regression test for enthought/pyface#272. application = SimpleApplication() application_running = [] def exit_app(): # Record whether the event loop is running or not, then exit. application_running.append(is_event_loop_running_qt4()) application.stop() application.on_trait_change(exit_app, 'application_running') # Make sure that the application stops after 10 seconds, no matter # what. qt_app = get_app_qt4() timeout_timer = QtCore.QTimer() timeout_timer.setSingleShot(True) timeout_timer.setInterval(10000) # 10 second timeout timeout_timer.timeout.connect(qt_app.quit) timeout_timer.start() try: application.start() finally: timeout_timer.stop() # Attempt to leave the QApplication in a reasonably clean # state in case of failure. qt_app.sendPostedEvents() qt_app.flush() self.assertTrue(application_running[0])
def open_and_wait(self, when_opened, *args, **kwargs): """ Execute the function to open the dialog and wait to be closed. Parameters ---------- when_opened : callable A callable to be called when the dialog has been created and opened. The callable with be called with the tester instance as argument. *args, **kwargs : Additional arguments to be passed to the `function` attribute of the tester. Raises ------ AssertionError if an assertion error was captured during the deferred calls that open and close the dialog. RuntimeError if the dialog has not been closed within 15 seconds after calling `self.function`. Any other exception that was captured during the deferred calls that open and close the dialog. .. note:: This method is synchronous """ condition_timer = QtCore.QTimer() def handler(): """ Run the when_opened as soon as the dialog has opened. """ if self.dialog_opened(): self._dialog_widget = self.get_dialog_widget() self._gui.invoke_later(when_opened, self) self.dialog_was_opened = True else: condition_timer.start() def condition(): if self._dialog_widget is None: return False else: return self.get_dialog_widget() != self._dialog_widget # Setup and start the timer to signal the handler every 100 msec. condition_timer.setInterval(100) condition_timer.setSingleShot(True) condition_timer.timeout.connect(handler) condition_timer.start() self._assigned = False try: # open the dialog on a deferred call. self._gui.invoke_later(self.open, *args, **kwargs) # wait in the event loop until timeout or a return value assigned. self._helper.event_loop_until_condition( condition=condition, timeout=15) finally: condition_timer.stop() condition_timer.timeout.disconnect(handler) self.assert_no_errors_collected()
def event_loop_until_condition(self, condition, timeout=10.0): """Runs the real Qt event loop until the provided condition evaluates to True. Raises ConditionTimeoutError if the timeout occurs before the condition is satisfied. Parameters ---------- condition : callable A callable to determine if the stop criteria have been met. This should accept no arguments. timeout : float Number of seconds to run the event loop in the case that the trait change does not occur. Notes ----- `timeout` is rounded to the nearest millisecond. """ def handler(): if condition(): self.qt_app.quit() # Make sure we don't get a premature exit from the event loop. with dont_quit_when_last_window_closed(self.qt_app): condition_timer = QtCore.QTimer() condition_timer.setInterval(50) condition_timer.timeout.connect(handler) timeout_timer = QtCore.QTimer() timeout_timer.setSingleShot(True) timeout_timer.setInterval(round(timeout * 1000)) timeout_timer.timeout.connect(self.qt_app.quit) timeout_timer.start() condition_timer.start() try: self.qt_app.exec_() if not condition(): raise ConditionTimeoutError( "Timed out waiting for condition") finally: timeout_timer.stop() condition_timer.stop()
def __init__(self, parent=None, delay=500, callback=None): super(MySearchLineEdit, self).__init__(parent) self.delay = delay self.callback = callback self.timer = QtCore.QTimer(self) self.timer.setSingleShot(True) self.setTextMargins(20, 0, 0, 0) self.connect(self, QtCore.SIGNAL("textEdited(QString)"), self.eventDelay) self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.startCallback)
def writeMode(self, new_mode): ''' Set the variable which keeps track of which tab is currently selected ''' self.animation_timer.stop() self.animating = False self.mode = new_mode self.animation_timer = QtCore.QTimer() if self.mode == 'Stationary States': self.stationaryMode() elif self.mode == 'Coherences': self.coherencesMode() elif self.mode == 'Avoided Crossing': self.crossingsMode()
def init(self, parent): self.control = QImageView() self._widget = QtGui.QWidget() self.drawing = False self.control.mousePressEvent = self.set_drawing self.control.mouseReleaseEvent = self.unset_drawing self.control.mouseMoveEvent = self.draw_pixel self.update_editor() # Set up timed events self._widget.timer = QtCore.QTimer() self._widget.timer.start(self.factory.update_ms) self._widget.timer.timeout.connect(self.object.evolve_board) self._widget.timer.timeout.connect(self.update_editor)
def wait_for_qt_signal(qt_signal, timeout): """ Wait for the given Qt signal to fire, or timeout. A mock implementation of QSignalSpy.wait, which is one of the missing bindings in PySide2, and is not available in Qt4. Parameters ---------- qt_signal : signal Qt signal to wait for timeout : int Timeout in milliseconds, to match Qt API. Raises ------ RuntimeError """ from pyface.qt import QtCore # QEventLoop is used instead of QApplication due to observed # hangs with Qt4. event_loop = QtCore.QEventLoop() def exit(*args, **kwargs): event_loop.quit() timeout_timer = QtCore.QTimer() timeout_timer.setSingleShot(True) timeout_timer.setInterval(timeout) timeout_timer.timeout.connect(exit) qt_signal.connect(exit) timeout_timer.start() event_loop.exec_() qt_signal.disconnect(exit) if timeout_timer.isActive(): timeout_timer.stop() else: raise RuntimeError("Timeout waiting for signal.")
def __init__(self, stationary_orbital, ket_orbital, bra_orbital, signals, zoom, points): object.__init__(self) self.stationary_orbital = stationary_orbital self.ket_orbital = ket_orbital self.bra_orbital = bra_orbital self.times = np.linspace(0, 2 * np.pi, 100) self.signals = signals self.zoom = zoom self.points = points self.mode = 'Stationary States' self.coherence = True self.rabi = False self.fid = False self.animating = False self.i = 0 self.phi, self.theta = np.mgrid[0:np.pi:50j, 0:2 * np.pi:100j] self.signals.orbital_change.connect(self.orbitalChange) self.signals.animate_orbital.connect(self.animateClicked) self.signals.cycle_change.connect(self.cycleChanged) self.animation_timer = QtCore.QTimer() self.animation_timer.timeout.connect(self.runStationary)
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) # Get the data for the avoided crossing pickle_foldername = os.path.join(os.getcwd(), 'Crossings_Data') pickle_filename = os.path.join(pickle_foldername, 'pickled_data.p') with open(pickle_filename, 'r') as file: pickled_data = pickle.load(file) self.bond_lengths = pickled_data['bond_lengths'] self.Low_A_Curve = pickled_data['Low_A_Curve'] self.High_A_Curve = pickled_data['High_A_Curve'] self.Low_D_Curve = pickled_data['Low_D_Curve'] self.High_D_Curve = pickled_data['High_D_Curve'] self.Low_A_MO = pickled_data['Low_A_MO'] self.High_A_MO = pickled_data['High_A_MO'] self.Low_D_MO = pickled_data['Low_D_MO'] self.High_D_MO = pickled_data['High_D_MO'] self.a_curves = True # Now set up the GUI self.layout = QtGui.QVBoxLayout(self) self.options = QtGui.QHBoxLayout() self.adiabat = QtGui.QRadioButton(self, text='Adiabatic Curves') self.adiabat.setChecked(True) self.options.addWidget(self.adiabat) self.adiabat.clicked.connect(self.changeCurves) self.diabat = QtGui.QRadioButton(self, text='Diabatic Curves') self.options.addWidget(self.diabat) self.diabat.clicked.connect(self.changeCurves) self.i_button = InstructionsButton(self, my_file='Crossing.txt') self.options.addWidget(self.i_button) self.layout.addLayout(self.options) self.plot_object = pg.PlotWidget() self.plot_object.getPlotItem().setMouseEnabled(False, False) self.plot_object.setLabel('bottom', 'Bond Length', units='α') self.plot_object.setLabel('left', 'Energy') self.plot_object.hideAxis('left') # Create and add things to the plot widget self.curve_AH = pg.PlotCurveItem(pen=(30, 100)) self.curve_AH.setData(self.bond_lengths, self.High_A_Curve) self.plot_object.addItem(self.curve_AH) self.curve_AL = pg.PlotCurveItem(pen=(20, 100)) self.curve_AL.setData(self.bond_lengths, self.Low_A_Curve) self.plot_object.addItem(self.curve_AL) self.curve_DH = pg.PlotCurveItem(pen=(90, 100)) self.curve_DH.setData(self.bond_lengths, self.High_D_Curve) self.plot_object.addItem(self.curve_DH) self.curve_DL = pg.PlotCurveItem(pen=(80, 100)) self.curve_DL.setData(self.bond_lengths, self.Low_D_Curve) self.plot_object.addItem(self.curve_DL) self.curser = pg.InfiniteLine(pos=0, angle=90, bounds=[1.5, 5.0], pen=pg.mkPen(width=3, color='g'), movable=True) self.curser.sigPositionChanged.connect(self.curserMoved) self.plot_object.addItem(self.curser) self.layout.addWidget(self.plot_object) self.layout.addItem(VerticalSpacer()) self.animate_button = QtGui.QPushButton(self, text='Start/Stop Animation') self.layout.addWidget(self.animate_button) self.animate_button.clicked.connect(self.animationPressed) self.animating = False self.animation_timer = QtCore.QTimer() self.animation_timer.timeout.connect(self.animateFrame) self.vid_frame = 0