本文整理汇总了Python中qtpy.QtCore.QTimer.setInterval方法的典型用法代码示例。如果您正苦于以下问题:Python QTimer.setInterval方法的具体用法?Python QTimer.setInterval怎么用?Python QTimer.setInterval使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qtpy.QtCore.QTimer
的用法示例。
在下文中一共展示了QTimer.setInterval方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MatplotlibDataViewer
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
class MatplotlibDataViewer(MatplotlibViewerMixin, DataViewer):
_state_cls = MatplotlibDataViewerState
tools = ['mpl:home', 'mpl:pan', 'mpl:zoom']
subtools = {'save': ['mpl:save']}
def __init__(self, session, parent=None, wcs=None, state=None):
super(MatplotlibDataViewer, self).__init__(session, parent=parent, state=state)
# Use MplWidget to set up a Matplotlib canvas inside the Qt window
self.mpl_widget = MplWidget()
self.setCentralWidget(self.mpl_widget)
# TODO: shouldn't have to do this
self.central_widget = self.mpl_widget
self.figure, self.axes = init_mpl(self.mpl_widget.canvas.fig, wcs=wcs)
MatplotlibViewerMixin.setup_callbacks(self)
self.central_widget.resize(600, 400)
self.resize(self.central_widget.size())
self._monitor_computation = QTimer()
self._monitor_computation.setInterval(500)
self._monitor_computation.timeout.connect(self._update_computation)
def _update_computation(self, message=None):
# If we get a ComputationStartedMessage and the timer isn't currently
# active, then we start the timer but we then return straight away.
# This is to avoid showing the 'Computing' message straight away in the
# case of reasonably fast operations.
if isinstance(message, ComputationStartedMessage):
if not self._monitor_computation.isActive():
self._monitor_computation.start()
return
for layer_artist in self.layers:
if layer_artist.is_computing:
self.loading_rectangle.set_visible(True)
text = self.loading_text.get_text()
if text.count('.') > 2:
text = 'Computing'
else:
text += '.'
self.loading_text.set_text(text)
self.loading_text.set_visible(True)
self.redraw()
return
self.loading_rectangle.set_visible(False)
self.loading_text.set_visible(False)
self.redraw()
# If we get here, the computation has stopped so we can stop the timer
self._monitor_computation.stop()
示例2: BaseTimerStatus
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
class BaseTimerStatus(StatusBarWidget):
"""Status bar widget base for widgets that update based on timers."""
def __init__(self, parent, statusbar):
"""Status bar widget base for widgets that update based on timers."""
self.timer = None # Needs to come before parent call
super(BaseTimerStatus, self).__init__(parent, statusbar)
self._interval = 2000
# Widget setup
fm = self.label_value.fontMetrics()
self.label_value.setMinimumWidth(fm.width('000%'))
# Setup
if self.is_supported():
self.timer = QTimer()
self.timer.timeout.connect(self.update_status)
self.timer.start(self._interval)
else:
self.hide()
def setVisible(self, value):
"""Override Qt method to stops timers if widget is not visible."""
if self.timer is not None:
if value:
self.timer.start(self._interval)
else:
self.timer.stop()
super(BaseTimerStatus, self).setVisible(value)
def set_interval(self, interval):
"""Set timer interval (ms)."""
self._interval = interval
if self.timer is not None:
self.timer.setInterval(interval)
def import_test(self):
"""Raise ImportError if feature is not supported."""
raise NotImplementedError
def is_supported(self):
"""Return True if feature is supported."""
try:
self.import_test()
return True
except ImportError:
return False
def get_value(self):
"""Return formatted text value."""
raise NotImplementedError
def update_status(self):
"""Update status label widget, if widget is visible."""
if self.isVisible():
self.label_value.setText(self.get_value())
示例3: embed
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
def embed(aQObject):
tag = "__eventletEmbededTimer__"
timer = QTimer()
timer.setSingleShot(True)
timer.setInterval(0.1)
timer.timeout.connect(functools.partial(_timerOnTimeout, timer))
timer.start()
aQObject.setProperty(tag, timer)
示例4: ConnectionInspector
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
class ConnectionInspector(QWidget):
def __init__(self, parent=None):
super(ConnectionInspector, self).__init__(parent, Qt.Window)
connections = self.fetch_data()
self.table_view = ConnectionTableView(connections, self)
self.setLayout(QVBoxLayout(self))
self.layout().addWidget(self.table_view)
button_layout = QHBoxLayout()
self.layout().addItem(button_layout)
self.save_status_label = QLabel(self)
button_layout.addWidget(self.save_status_label)
button_layout.addStretch()
self.save_button = QPushButton(self)
self.save_button.setText("Save list to file...")
self.save_button.clicked.connect(self.save_list_to_file)
button_layout.addWidget(self.save_button)
self.update_timer = QTimer(parent=self)
self.update_timer.setInterval(1500)
self.update_timer.timeout.connect(self.update_data)
self.update_timer.start()
def update_data(self):
self.table_view.model().connections = self.fetch_data()
def fetch_data(self):
plugins = data_plugins.plugin_modules
return [connection
for p in plugins.values()
for connection in p.connections.values()
]
@Slot()
def save_list_to_file(self):
filename, filters = QFileDialog.getSaveFileName(self,
"Save connection list",
"",
"Text Files (*.txt)")
try:
with open(filename, "w") as f:
for conn in self.table_view.model().connections:
f.write(
"{p}://{a}\n".format(p=conn.protocol, a=conn.address))
self.save_status_label.setText("File saved to {}".format(filename))
except Exception as e:
msgBox = QMessageBox()
msgBox.setText("Couldn't save connection list to file.")
msgBox.setInformativeText("Error: {}".format(str(e)))
msgBox.setStandardButtons(QMessageBox.Ok)
msgBox.exec_()
示例5: BaseTimerStatus
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
class BaseTimerStatus(StatusBarWidget):
TITLE = None
TIP = None
def __init__(self, parent, statusbar):
StatusBarWidget.__init__(self, parent, statusbar)
self.setToolTip(self.TIP)
layout = self.layout()
layout.addWidget(QLabel(self.TITLE))
self.label = QLabel()
self.label.setFont(self.label_font)
layout.addWidget(self.label)
layout.addSpacing(20)
if self.is_supported():
self.timer = QTimer()
self.timer.timeout.connect(self.update_label)
self.timer.start(2000)
else:
self.timer = None
self.hide()
def set_interval(self, interval):
"""Set timer interval (ms)"""
if self.timer is not None:
self.timer.setInterval(interval)
def import_test(self):
"""Raise ImportError if feature is not supported"""
raise NotImplementedError
def is_supported(self):
"""Return True if feature is supported"""
try:
self.import_test()
return True
except ImportError:
return False
def get_value(self):
"""Return value (e.g. CPU or memory usage)"""
raise NotImplementedError
def update_label(self):
"""Update status label widget, if widget is visible"""
if self.isVisible():
self.label.setText('%d %%' % self.get_value())
示例6: create_app
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
def create_app(datafiles=[], interactive=True):
app = get_qapp()
if interactive:
# Splash screen
splash = get_splash()
splash.image = QtGui.QPixmap(MOSVIZ_SPLASH_PATH)
splash.show()
else:
splash = None
# Start off by loading plugins. We need to do this before restoring
# the session or loading the configuration since these may use existing
# plugins.
load_plugins(splash=splash)
# # Show the splash screen for 2 seconds
if interactive:
timer = QTimer()
timer.setInterval(2000)
timer.setSingleShot(True)
timer.timeout.connect(splash.close)
timer.start()
data_collection = glue.core.DataCollection()
hub = data_collection.hub
if interactive:
splash.set_progress(100)
ga = _create_glue_app(data_collection, hub)
ga.run_startup_action('mosviz')
# Load the data files.
if datafiles:
datasets = load_data_files(datafiles)
ga.add_datasets(data_collection, datasets, auto_merge=False)
return ga
示例7: _CondaAPI
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
class _CondaAPI(QObject):
"""
"""
ROOT_PREFIX = None
ENCODING = 'ascii'
UTF8 = 'utf-8'
DEFAULT_CHANNELS = ['https://repo.continuum.io/pkgs/pro',
'https://repo.continuum.io/pkgs/free']
def __init__(self, parent=None):
super(_CondaAPI, self).__init__()
self._parent = parent
self._queue = deque()
self._timer = QTimer()
self._current_worker = None
self._workers = []
self._timer.setInterval(1000)
self._timer.timeout.connect(self._clean)
self.set_root_prefix()
def _clean(self):
"""
Periodically check for inactive workers and remove their references.
"""
if self._workers:
for w in self._workers:
if w.is_finished():
self._workers.remove(w)
else:
self._current_worker = None
self._timer.stop()
def _start(self):
"""
"""
if len(self._queue) == 1:
self._current_worker = self._queue.popleft()
self._workers.append(self._current_worker)
self._current_worker.start()
self._timer.start()
def is_active(self):
"""
Check if a worker is still active.
"""
return len(self._workers) == 0
def terminate_all_processes(self):
"""
Kill all working processes.
"""
for worker in self._workers:
worker.close()
# --- Conda api
# -------------------------------------------------------------------------
def _call_conda(self, extra_args, abspath=True, parse=False,
callback=None):
"""
Call conda with the list of extra arguments, and return the worker.
The result can be force by calling worker.communicate(), which returns
the tuple (stdout, stderr).
"""
if abspath:
if sys.platform == 'win32':
python = join(self.ROOT_PREFIX, 'python.exe')
conda = join(self.ROOT_PREFIX, 'Scripts',
'conda-script.py')
else:
python = join(self.ROOT_PREFIX, 'bin/python')
conda = join(self.ROOT_PREFIX, 'bin/conda')
cmd_list = [python, conda]
else:
# Just use whatever conda is on the path
cmd_list = ['conda']
cmd_list.extend(extra_args)
process_worker = ProcessWorker(cmd_list, parse=parse,
callback=callback)
process_worker.sig_finished.connect(self._start)
self._queue.append(process_worker)
self._start()
return process_worker
def _call_and_parse(self, extra_args, abspath=True, callback=None):
"""
"""
return self._call_conda(extra_args, abspath=abspath, parse=True,
callback=callback)
def _setup_install_commands_from_kwargs(self, kwargs, keys=tuple()):
cmd_list = []
if kwargs.get('override_channels', False) and 'channel' not in kwargs:
raise TypeError('conda search: override_channels requires channel')
if 'env' in kwargs:
#.........这里部分代码省略.........
示例8: _DownloadAPI
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
class _DownloadAPI(QObject):
"""
Download API based on QNetworkAccessManager
"""
def __init__(self, chunk_size=1024):
super(_DownloadAPI, self).__init__()
self._chunk_size = chunk_size
self._head_requests = {}
self._get_requests = {}
self._paths = {}
self._workers = {}
self._manager = QNetworkAccessManager(self)
self._timer = QTimer()
# Setup
self._timer.setInterval(1000)
self._timer.timeout.connect(self._clean)
# Signals
self._manager.finished.connect(self._request_finished)
self._manager.sslErrors.connect(self._handle_ssl_errors)
def _handle_ssl_errors(self, reply, errors):
logger.error(str(('SSL Errors', errors)))
def _clean(self):
"""
Periodically check for inactive workers and remove their references.
"""
if self._workers:
for url in self._workers.copy():
w = self._workers[url]
if w.is_finished():
self._workers.pop(url)
self._paths.pop(url)
if url in self._get_requests:
self._get_requests.pop(url)
else:
self._timer.stop()
def _request_finished(self, reply):
url = to_text_string(reply.url().toEncoded(), encoding='utf-8')
if url in self._paths:
path = self._paths[url]
if url in self._workers:
worker = self._workers[url]
if url in self._head_requests:
self._head_requests.pop(url)
start_download = True
header_pairs = reply.rawHeaderPairs()
headers = {}
for hp in header_pairs:
headers[to_text_string(hp[0]).lower()] = to_text_string(hp[1])
total_size = int(headers.get('content-length', 0))
# Check if file exists
if os.path.isfile(path):
file_size = os.path.getsize(path)
# Check if existing file matches size of requested file
start_download = file_size != total_size
if start_download:
# File sizes dont match, hence download file
qurl = QUrl(url)
request = QNetworkRequest(qurl)
self._get_requests[url] = request
reply = self._manager.get(request)
error = reply.error()
if error:
logger.error(str(('Reply Error:', error)))
reply.downloadProgress.connect(
lambda r, t, w=worker: self._progress(r, t, w))
else:
# File sizes match, dont download file
worker.finished = True
worker.sig_download_finished.emit(url, path)
worker.sig_finished.emit(worker, path, None)
elif url in self._get_requests:
data = reply.readAll()
self._save(url, path, data)
def _save(self, url, path, data):
"""
"""
worker = self._workers[url]
path = self._paths[url]
if len(data):
with open(path, 'wb') as f:
f.write(data)
#.........这里部分代码省略.........
示例9: ConnectionTableModel
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
class ConnectionTableModel(QAbstractTableModel):
def __init__(self, connections=[], parent=None):
super(ConnectionTableModel, self).__init__(parent=parent)
self._column_names = ("protocol", "address", "connected")
self.update_timer = QTimer(self)
self.update_timer.setInterval(1000)
self.update_timer.timeout.connect(self.update_values)
self.connections = connections
def sort(self, col, order=Qt.AscendingOrder):
if self._column_names[col] == "value":
return
self.layoutAboutToBeChanged.emit()
sort_reversed = (order == Qt.AscendingOrder)
self._connections.sort(key=attrgetter(self._column_names[col]), reverse=sort_reversed)
self.layoutChanged.emit()
@property
def connections(self):
return self._connections
@connections.setter
def connections(self, new_connections):
self.beginResetModel()
self._connections = new_connections
self.endResetModel()
if len(self._connections) > 0:
self.update_timer.start()
else:
self.update_timer.stop()
# QAbstractItemModel Implementation
def flags(self, index):
return Qt.ItemIsSelectable | Qt.ItemIsEnabled
def rowCount(self, parent=None):
if parent is not None and parent.isValid():
return 0
return len(self._connections)
def columnCount(self, parent=None):
return len(self._column_names)
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return QVariant()
if index.row() >= self.rowCount():
return QVariant()
if index.column() >= self.columnCount():
return QVariant()
column_name = self._column_names[index.column()]
conn = self.connections[index.row()]
if role == Qt.DisplayRole or role == Qt.EditRole:
return str(getattr(conn, column_name))
else:
return QVariant()
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role != Qt.DisplayRole:
return super(ConnectionTableModel, self).headerData(
section, orientation, role)
if orientation == Qt.Horizontal and section < self.columnCount():
return str(self._column_names[section]).capitalize()
elif orientation == Qt.Vertical and section < self.rowCount():
return section
# End QAbstractItemModel implementation.
@Slot()
def update_values(self):
self.dataChanged.emit(self.index(0,2), self.index(self.rowCount(),2))
示例10: ProcessWorker
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
class ProcessWorker(QObject):
"""Process worker based on a QProcess for non blocking UI."""
sig_started = Signal(object)
sig_finished = Signal(object, object, object)
sig_partial = Signal(object, object, object)
def __init__(self, cmd_list, environ=None):
"""
Process worker based on a QProcess for non blocking UI.
Parameters
----------
cmd_list : list of str
Command line arguments to execute.
environ : dict
Process environment,
"""
super(ProcessWorker, self).__init__()
self._result = None
self._cmd_list = cmd_list
self._fired = False
self._communicate_first = False
self._partial_stdout = None
self._started = False
self._timer = QTimer()
self._process = QProcess()
self._set_environment(environ)
self._timer.setInterval(150)
self._timer.timeout.connect(self._communicate)
self._process.readyReadStandardOutput.connect(self._partial)
def _get_encoding(self):
"""Return the encoding/codepage to use."""
enco = 'utf-8'
# Currently only cp1252 is allowed?
if WIN:
import ctypes
codepage = to_text_string(ctypes.cdll.kernel32.GetACP())
# import locale
# locale.getpreferredencoding() # Differences?
enco = 'cp' + codepage
return enco
def _set_environment(self, environ):
"""Set the environment on the QProcess."""
if environ:
q_environ = self._process.processEnvironment()
for k, v in environ.items():
q_environ.insert(k, v)
self._process.setProcessEnvironment(q_environ)
def _partial(self):
"""Callback for partial output."""
raw_stdout = self._process.readAllStandardOutput()
stdout = handle_qbytearray(raw_stdout, self._get_encoding())
if self._partial_stdout is None:
self._partial_stdout = stdout
else:
self._partial_stdout += stdout
self.sig_partial.emit(self, stdout, None)
def _communicate(self):
"""Callback for communicate."""
if (not self._communicate_first and
self._process.state() == QProcess.NotRunning):
self.communicate()
elif self._fired:
self._timer.stop()
def communicate(self):
"""Retrieve information."""
self._communicate_first = True
self._process.waitForFinished()
enco = self._get_encoding()
if self._partial_stdout is None:
raw_stdout = self._process.readAllStandardOutput()
stdout = handle_qbytearray(raw_stdout, enco)
else:
stdout = self._partial_stdout
raw_stderr = self._process.readAllStandardError()
stderr = handle_qbytearray(raw_stderr, enco)
result = [stdout.encode(enco), stderr.encode(enco)]
if PY2:
stderr = stderr.decode()
result[-1] = ''
self._result = result
if not self._fired:
self.sig_finished.emit(self, result[0], result[-1])
#.........这里部分代码省略.........
示例11: _RequestsDownloadAPI
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
class _RequestsDownloadAPI(QObject):
"""
"""
_sig_download_finished = Signal(str, str)
_sig_download_progress = Signal(str, str, int, int)
def __init__(self):
super(QObject, self).__init__()
self._conda_api = CondaAPI()
self._queue = deque()
self._threads = []
self._workers = []
self._timer = QTimer()
self._chunk_size = 1024
self._timer.setInterval(1000)
self._timer.timeout.connect(self._clean)
def _clean(self):
"""
Periodically check for inactive workers and remove their references.
"""
if self._workers:
for w in self._workers:
if w.is_finished():
self._workers.remove(w)
if self._threads:
for t in self._threads:
if t.isFinished():
self._threads.remove(t)
else:
self._timer.stop()
def _start(self):
"""
"""
if len(self._queue) == 1:
thread = self._queue.popleft()
thread.start()
self._timer.start()
def _create_worker(self, method, *args, **kwargs):
"""
"""
# FIXME: this might be heavy...
thread = QThread()
worker = RequestsDownloadWorker(method, args, kwargs)
worker.moveToThread(thread)
worker.sig_finished.connect(self._start)
self._sig_download_finished.connect(worker.sig_download_finished)
self._sig_download_progress.connect(worker.sig_download_progress)
worker.sig_finished.connect(thread.quit)
thread.started.connect(worker.start)
self._queue.append(thread)
self._threads.append(thread)
self._workers.append(worker)
self._start()
return worker
def _download(self, url, path=None, force=False):
"""
"""
if path is None:
path = url.split('/')[-1]
# Make dir if non existent
folder = os.path.dirname(os.path.abspath(path))
if not os.path.isdir(folder):
os.makedirs(folder)
# Start actual download
try:
r = requests.get(url, stream=True)
except Exception as error:
logger.error(str(error))
# Break if error found!
# self._sig_download_finished.emit(url, path)
# return path
total_size = int(r.headers.get('Content-Length', 0))
# Check if file exists
if os.path.isfile(path) and not force:
file_size = os.path.getsize(path)
# Check if existing file matches size of requested file
if file_size == total_size:
self._sig_download_finished.emit(url, path)
return path
# File not found or file size did not match. Download file.
progress_size = 0
with open(path, 'wb') as f:
for chunk in r.iter_content(chunk_size=self._chunk_size):
if chunk:
f.write(chunk)
progress_size += len(chunk)
self._sig_download_progress.emit(url, path,
#.........这里部分代码省略.........
示例12: BasePlot
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
#.........这里部分代码省略.........
return self.plotItem.getViewBox().state['mouseEnabled'][1]
@mouseEnabledY.setter
def mouseEnabledY(self, y_enabled):
"""
Whether or not mouse interactions are enabled for the Y-axis.
Parameters
-------
y_enabled : bool
"""
self.plotItem.setMouseEnabled(y=y_enabled)
@Property(int)
def maxRedrawRate(self):
"""
The maximum rate (in Hz) at which the plot will be redrawn.
The plot will not be redrawn if there is not new data to draw.
Returns
-------
int
"""
return self._redraw_rate
@maxRedrawRate.setter
def maxRedrawRate(self, redraw_rate):
"""
The maximum rate (in Hz) at which the plot will be redrawn.
The plot will not be redrawn if there is not new data to draw.
Parameters
-------
redraw_rate : int
"""
self._redraw_rate = redraw_rate
self.redraw_timer.setInterval(int((1.0/self._redraw_rate)*1000))
def pausePlotting(self):
self.redraw_timer.stop() if self.redraw_timer.isActive() else self.redraw_timer.start()
return self.redraw_timer.isActive()
def mouseMoved(self, evt):
"""
A handler for the crosshair feature. Every time the mouse move, the mouse coordinates are updated, and the
horizontal and vertical hairlines will be redrawn at the new coordinate. If a PyDMDisplay object is available,
that display will also have the x- and y- values to update on the UI.
Parameters
-------
evt: MouseEvent
The mouse event type, from which the mouse coordinates are obtained.
"""
pos = evt[0]
if self.sceneBoundingRect().contains(pos):
mouse_point = self.getViewBox().mapSceneToView(pos)
self.vertical_crosshair_line.setPos(mouse_point.x())
self.horizontal_crosshair_line.setPos(mouse_point.y())
self.crosshair_position_updated.emit(mouse_point.x(), mouse_point.y())
def enableCrosshair(self, is_enabled, starting_x_pos, starting_y_pos, vertical_angle=90, horizontal_angle=0,
vertical_movable=False, horizontal_movable=False):
"""
Enable the crosshair to be drawn on the ViewBox.
Parameters
----------
is_enabled : bool
True is to draw the crosshair, False is to not draw.
starting_x_pos : float
The x coordinate where to start the vertical crosshair line.
starting_y_pos : float
The y coordinate where to start the horizontal crosshair line.
vertical_angle : float
The angle to tilt the vertical crosshair line. Default at 90 degrees.
horizontal_angle
The angle to tilt the horizontal crosshair line. Default at 0 degrees.
vertical_movable : bool
True if the vertical line can be moved by the user; False is not.
horizontal_movable
False if the horizontal line can be moved by the user; False is not.
"""
if is_enabled:
self.vertical_crosshair_line = InfiniteLine(pos=starting_x_pos, angle=vertical_angle,
movable=vertical_movable)
self.horizontal_crosshair_line = InfiniteLine(pos=starting_y_pos, angle=horizontal_angle,
movable=horizontal_movable)
self.plotItem.addItem(self.vertical_crosshair_line)
self.plotItem.addItem(self.horizontal_crosshair_line)
self.crosshair_movement_proxy = SignalProxy(self.plotItem.scene().sigMouseMoved, rateLimit=60,
slot=self.mouseMoved)
else:
if self.vertical_crosshair_line:
self.plotItem.removeItem(self.vertical_crosshair_line)
if self.horizontal_crosshair_line:
self.plotItem.removeItem(self.horizontal_crosshair_line)
if self.crosshair_movement_proxy:
self.crosshair_movement_proxy.disconnect()
示例13: start_glue
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
def start_glue(gluefile=None, config=None, datafiles=None, maximized=True):
"""Run a glue session and exit
Parameters
----------
gluefile : str
An optional ``.glu`` file to restore.
config : str
An optional configuration file to use.
datafiles : str
An optional list of data files to load.
maximized : bool
Maximize screen on startup. Otherwise, use default size.
"""
import glue
from glue.utils.qt import get_qapp
app = get_qapp()
splash = get_splash()
splash.show()
# Start off by loading plugins. We need to do this before restoring
# the session or loading the configuration since these may use existing
# plugins.
load_plugins(splash=splash)
from glue.app.qt import GlueApplication
datafiles = datafiles or []
hub = None
if gluefile is not None:
app = restore_session(gluefile)
return app.start()
if config is not None:
glue.env = glue.config.load_configuration(search_path=[config])
data_collection = glue.core.DataCollection()
hub = data_collection.hub
splash.set_progress(100)
session = glue.core.Session(data_collection=data_collection, hub=hub)
ga = GlueApplication(session=session)
from qtpy.QtCore import QTimer
timer = QTimer()
timer.setInterval(1000)
timer.setSingleShot(True)
timer.timeout.connect(splash.close)
timer.start()
if datafiles:
datasets = load_data_files(datafiles)
ga.add_datasets(data_collection, datasets)
return ga.start(maximized=maximized)
示例14: DesignerHooks
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
class DesignerHooks(object):
"""
Class that handles the integration with PyDM and the Qt Designer
by hooking up slots to signals provided by FormEditor and other classes.
"""
__instance = None
def __init__(self):
if self.__initialized:
return
self.__form_editor = None
self.__initialized = True
self.__timer = None
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = object.__new__(DesignerHooks)
cls.__instance.__initialized = False
return cls.__instance
@property
def form_editor(self):
return self.__form_editor
@form_editor.setter
def form_editor(self, editor):
if self.form_editor is not None:
return
if not editor:
return
self.__form_editor = editor
self.setup_hooks()
def setup_hooks(self):
# Set PyDM to be read-only
data_plugins.set_read_only(True)
if self.form_editor:
fwman = self.form_editor.formWindowManager()
if fwman:
fwman.formWindowAdded.connect(
self.__new_form_added
)
def __new_form_added(self, form_window_interface):
style_data = stylesheet._get_style_data(None)
widget = form_window_interface.formContainer()
widget.setStyleSheet(style_data)
if not self.__timer:
self.__start_kicker()
def __kick(self):
fwman = self.form_editor.formWindowManager()
if fwman:
widget = fwman.activeFormWindow()
if widget:
widget.update()
def __start_kicker(self):
self.__timer = QTimer()
self.__timer.setInterval(100)
self.__timer.timeout.connect(self.__kick)
self.__timer.start()
示例15: _DownloadAPI
# 需要导入模块: from qtpy.QtCore import QTimer [as 别名]
# 或者: from qtpy.QtCore.QTimer import setInterval [as 别名]
class _DownloadAPI(QObject):
"""Download API based on QNetworkAccessManager."""
def __init__(self, chunk_size=1024, load_rc_func=None):
"""Download API based on QNetworkAccessManager."""
super(_DownloadAPI, self).__init__()
self._chunk_size = chunk_size
self._head_requests = {}
self._get_requests = {}
self._paths = {}
self._workers = {}
self._load_rc_func = load_rc_func
self._manager = QNetworkAccessManager(self)
self._proxy_factory = NetworkProxyFactory(load_rc_func=load_rc_func)
self._timer = QTimer()
# Setup
self._manager.setProxyFactory(self._proxy_factory)
self._timer.setInterval(1000)
self._timer.timeout.connect(self._clean)
# Signals
self._manager.finished.connect(self._request_finished)
self._manager.sslErrors.connect(self._handle_ssl_errors)
self._manager.proxyAuthenticationRequired.connect(
self._handle_proxy_auth)
@staticmethod
def _handle_ssl_errors(reply, errors):
"""Callback for ssl_errors."""
logger.error(str(('SSL Errors', errors, reply)))
@staticmethod
def _handle_proxy_auth(proxy, authenticator):
"""Callback for ssl_errors."""
# authenticator.setUser('1')`
# authenticator.setPassword('1')
logger.error(str(('Proxy authentication Error. '
'Enter credentials in condarc',
proxy,
authenticator)))
def _clean(self):
"""Check for inactive workers and remove their references."""
if self._workers:
for url in self._workers.copy():
w = self._workers[url]
if w.is_finished():
self._workers.pop(url)
self._paths.pop(url)
if url in self._get_requests:
self._get_requests.pop(url)
else:
self._timer.stop()
def _request_finished(self, reply):
"""Callback for download once the request has finished."""
url = to_text_string(reply.url().toEncoded(), encoding='utf-8')
if url in self._paths:
path = self._paths[url]
if url in self._workers:
worker = self._workers[url]
if url in self._head_requests:
error = reply.error()
# print(url, error)
if error:
logger.error(str(('Head Reply Error:', error)))
worker.sig_download_finished.emit(url, path)
worker.sig_finished.emit(worker, path, error)
return
self._head_requests.pop(url)
start_download = not bool(error)
header_pairs = reply.rawHeaderPairs()
headers = {}
for hp in header_pairs:
headers[to_text_string(hp[0]).lower()] = to_text_string(hp[1])
total_size = int(headers.get('content-length', 0))
# Check if file exists
if os.path.isfile(path):
file_size = os.path.getsize(path)
# Check if existing file matches size of requested file
start_download = file_size != total_size
if start_download:
# File sizes dont match, hence download file
qurl = QUrl(url)
request = QNetworkRequest(qurl)
self._get_requests[url] = request
reply = self._manager.get(request)
error = reply.error()
#.........这里部分代码省略.........