本文整理汇总了Python中PySide.QtCore.QTimer.isActive方法的典型用法代码示例。如果您正苦于以下问题:Python QTimer.isActive方法的具体用法?Python QTimer.isActive怎么用?Python QTimer.isActive使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PySide.QtCore.QTimer
的用法示例。
在下文中一共展示了QTimer.isActive方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Panel
# 需要导入模块: from PySide.QtCore import QTimer [as 别名]
# 或者: from PySide.QtCore.QTimer import isActive [as 别名]
class Panel(QWidget):
def __init__(self, parent=None, instr=None, lock=None, title="Instrument Panel"):
# This class derivates from a Qt Widget so we have to call
# the class builder ".__init__()"
QWidget.__init__(self)
# "self" is now a Qt Widget, then we load the user interface
# generated with QtDesigner and call it self.ui
self.ui = Keithley6221_Ui.Ui_Panel()
# Now we have to feed the GUI building method of this object (self.ui)
# with the current Qt Widget 'self', but the widgets from the design will actually be built as children
# of the object self.ui
self.ui.setupUi(self)
self.setWindowTitle(title)
self.reserved_access_to_instr = lock
self.instr = instr
self.monitor_timer = QTimer()
# The timer would not wait for the completion of the task otherwise
self.monitor_timer.setSingleShot(True)
self.monitor_timer.timeout.connect(self.monitor)
self.firsttime = 0
# bug: if the box is checked in the .ui file, the system freezes
# if self.ui.monitor.isChecked():self.monitor()
def monitor(self, state=1):
if state != 1:
self.monitor_timer.stop()
elif state and not (self.monitor_timer.isActive()):
with self.reserved_access_to_instr:
I = self.instr.query_current_source_amplitude()
Vcomp = self.instr.query_voltage_compliance()
outstate = self.instr.query_output_ON()
self.ui.I_disp.setText(str(I * 1e6) + u" μA")
self.ui.V_disp.setText(str(Vcomp) + " V")
self.ui.outputON.setChecked(outstate)
self.monitor_timer.start(self.ui.refresh_rate.value() * 1000)
def update_timer_timeout(self, secs):
# The value must be converted to milliseconds
self.monitor_timer.setInterval(secs * 1000)
def change_I(self, value=0):
with self.reserved_access_to_instr:
self.instr.set_current_source_amplitude(value * 1e6)
def change_V_comp(self, value=0):
with self.reserved_access_to_instr:
self.instr.set_voltage_compliance(value)
def switch_output(self, value=False):
if value:
with self.reserved_access_to_instr:
self.instr.output_ON()
else:
with self.reserved_access_to_instr:
self.instr.output_OFF()
def reset_inst(self):
with self.reserved_access_to_instr:
self.instr.reset()
示例2: open
# 需要导入模块: from PySide.QtCore import QTimer [as 别名]
# 或者: from PySide.QtCore.QTimer import isActive [as 别名]
def open(self, url, timeout=60):
"""Wait for download to complete and return result"""
loop = QEventLoop()
timer = QTimer()
timer.setSingleShot(True)
timer.timeout.connect(loop.quit)
self.loadFinished.connect(loop.quit)
self.load(QUrl(url))
timer.start(timeout * 1000)
loop.exec_() # delay here until download finished
if timer.isActive():
# downloaded successfully
timer.stop()
return self.html()
else:
# timed out
print 'Request timed out:', url
示例3: __init__
# 需要导入模块: from PySide.QtCore import QTimer [as 别名]
# 或者: from PySide.QtCore.QTimer import isActive [as 别名]
class GlobalTimer:
"""All parsing and highlighting is done in main loop thread.
If parsing is being done for long time, main loop gets blocked.
Therefore SyntaxHighlighter controls, how long parsign is going, and, if too long,
schedules timer and releases main loop.
One global timer is used by all Qutepart instances, because main loop time usage
must not depend on opened files count
"""
def __init__(self):
self._timer = QTimer()
self._timer.setSingleShot(True)
self._timer.timeout.connect(self._onTimer)
self._scheduledCallbacks = []
def isActive(self):
return self._timer.isActive()
def scheduleCallback(self, callback):
if not callback in self._scheduledCallbacks:
self._scheduledCallbacks.append(callback)
self._timer.start()
def unScheduleCallback(self, callback):
if callback in self._scheduledCallbacks:
self._scheduledCallbacks.remove(callback)
if not self._scheduledCallbacks:
self._timer.stop()
def isCallbackScheduled(self, callback):
return callback in self._scheduledCallbacks
def _onTimer(self):
if self._scheduledCallbacks:
callback = self._scheduledCallbacks.pop()
callback()
if self._scheduledCallbacks:
self._timer.start()
示例4: DisplayController
# 需要导入模块: from PySide.QtCore import QTimer [as 别名]
# 或者: from PySide.QtCore.QTimer import isActive [as 别名]
#.........这里部分代码省略.........
if not self.__display_view_initialized:
self.__display_app.close_login_view()
self.__display_app.init_display_view(result["setting"])
self.__display_view_initialized = True
if result["error"]:
self.__display_app.update_status_bar(UIStrings.SETTING_NOT_RECEIVED)
LOGGER.error(result["error"])
else:
self.__display_app.update_settings(result["setting"])
@Slot(dict)
def __connection_status_result(self, connection_status):
"""Slot function for connection status result
:param dict connection_status: dictionary containing network and internet status
"""
status = UIStrings.OK
color = "green"
if not connection_status["network"]:
color = "red"
status = UIStrings.NETWORK_DOWN
elif not connection_status["internet"]:
status = UIStrings.INTERNET_DOWN
color = "red"
self.__display_app.set_connection_status(status, color)
@Slot()
def __close(self):
""" Slot function when view gets closed
Tries to de-initialize the model and stop refresh graph timer if active
"""
if self.__refresh_graph_timer.isActive():
self.__refresh_graph_timer.stop()
LOGGER.debug("closing model")
if self.__model:
self.__model.close()
@Slot(MeasurementEvent)
def __measurement_changed(self, event):
""" Slot function which receives measurement event from model
:param MeasurementEvent event: Measurement Event object received from model
"""
if self.__refresh_graph_timer.isActive():
self.__refresh_graph_timer.stop()
self.temperature = event.temperature
self.humidity = event.humidity
self.__update_data(self.temperature, self.humidity)
self.__display_app.plot_graph(self.temperature_data, self.humidity_data)
self.__refresh_graph_timer.start(REFRESH_GRAPH_TIMEOUT)
@Slot()
def __speculate_data(self):
""" This function is a slot for refresh_graph timeout event
It updates measurement data with last received measurement values
"""
self.__update_data(self.temperature, self.humidity)
self.__display_app.plot_graph(self.temperature_data, self.humidity_data)
self.__refresh_graph_timer.start(REFRESH_GRAPH_TIMEOUT)
def __update_data(self, temperature, humidity):
""" Updates measurement data
示例5: Quiz
# 需要导入模块: from PySide.QtCore import QTimer [as 别名]
# 或者: from PySide.QtCore.QTimer import isActive [as 别名]
#.........这里部分代码省略.........
self.trayIcon.setIcon(QIcon(PATH_TO_RES + TRAY + 'active.png'))
self.pauseAction.setIcon(QIcon(PATH_TO_RES + TRAY + PAUSE_ICON))
else:
self.waitUntilNextTimeslot()
self.pauseAction.setText('&Pause')
# self.pauseAction.setShortcut('P')
self.trayIcon.setToolTip('Quiz in progress!')
self.trayIcon.setIcon(QIcon(PATH_TO_RES + TRAY + 'active.png'))
self.pauseAction.setIcon(QIcon(PATH_TO_RES + TRAY + PAUSE_ICON))
self.stats.pauseEnded()
self.updater.mayUpdate = False
else:
self.showSessionMessage(u'Sorry, cannot pause while quiz in progress!')
def showQuiz(self):
if self.isHidden():
self.updateContent()
self.setButtonsActions()
#self.restoreGeometry(self.gem)
self.trayIcon.setIcon(QIcon(PATH_TO_RES + TRAY + 'active.png'))
self.show()
self.setWindowOpacity(0)
self.fade()
self.countdown.setValue(self.options.getCountdownInterval() * 100)
self.beginCountdown()
self.stats.musingsStarted()
if self.nextQuizTimer.isActive(): self.nextQuizTimer.stop()
self.updater.mayUpdate = False
else:
self.showSessionMessage(u'Quiz is already underway!')
def showOptions(self):
self.optionsDialog.show()
def showAbout(self):
self.about.show()
def showQuickDict(self):
self.qdict.showQDict = True
def showGlobalStatistics(self):
self.statistics.show()
def showToolsDialog(self):
self.tools.show()
def showQuickLoad(self):
self.qload.show()
def startTrayLoading(self):
self.gifLoading.start()
#self.iconTimer = QTimer()
#self.iconTimer.timeout.connect(self.updateTrayIcon)
#self.iconTimer.start(100)
def stopTrayLoading(self):
self.gifLoading.stop()
def updateTrayIcon(self):
示例6: GameRunToAnthill
# 需要导入模块: from PySide.QtCore import QTimer [as 别名]
# 或者: from PySide.QtCore.QTimer import isActive [as 别名]
#.........这里部分代码省略.........
self.updateConstants()
def moveZombie(self):
for ant in self.ants:
if ant.zombie:
self._moveAnt(ant, ant.move)
def buildZombiePath(self):
self.message.sendMessage('zombie_waking_up')
self.repaint()
for ant in self.ants:
if ant.zombie:
ant.findWayToVerticalLine(self.field.finish_line_x + 100, self.isAntIntersectAnything)
self.message.noMessage()
self.repaint()
#--------------------- Game control ---------------------
def reverseCalculationWorker(self, seconds_before_start):
self.message.sendMessage('second_' + str(seconds_before_start))
if seconds_before_start == 0:
self.timer.start()
QTimer.singleShot(1000, self.message.noMessage)
self.repaint()
def fastStart(self):
self.game_started = True
self.buildZombiePath()
self.reverse_calculation.startReverseCalculation(0, self.reverseCalculationWorker)
def start(self):
self.game_started = True
self.buildZombiePath()
if self.timer.isActive():
self.fastStart()
else:
self.reverse_calculation.startReverseCalculation(3, self.reverseCalculationWorker)
def stop(self):
self.timer.stop()
self.message.sendMessage('pause')
self.repaint()
def restart(self):
self.init_game('restart')
self.repaint()
def doGameStep(self):
self.updateState()
self.processPressedKeys()
self.moveZombie()
self.checkFinishLine()
self.repaint()
#--------------------- I'm afraid. We need to use ... math! ---------------------
def _areTwoAntFinished(self):
finished_count = 0
for ant in self.ants:
if self.isAntFinished(ant):
finished_count += 1
return finished_count >= 2
def checkFinishLine(self):
if self.message.getMessageText() in tuple(ant.name + '_ant_wins' for ant in self.ants) or \
示例7: MainWindow
# 需要导入模块: from PySide.QtCore import QTimer [as 别名]
# 或者: from PySide.QtCore.QTimer import isActive [as 别名]
#.........这里部分代码省略.........
When any rendering option is changed this method is invoked. It polls
the GUI for the selected setting values and passes them to the 2D
world widget.
'''
self._worldWidget.setDrawActiveCells(self._openChk.isChecked())
self._worldWidget.setDrawVisitedCells(self._visitedChk.isChecked())
self._worldWidget.setDrawPath(self._pathChk.isChecked())
self._worldWidget.setDrawCosts(self._costChk.isChecked())
self._worldWidget.repaint()
@Slot()
def _onPercentSlideChange(self, value):
'''
Invoked every time the percent slider is changed. Displays the percent
value on the GUI.
'''
#Add extra padding to the front of the string to help prevent
#gui layout resizing
if value < 10:
self._percentLbl.setText(" " + str(value) + "%")
elif value < 100:
self._percentLbl.setText(" " + str(value) + "%")
else:
self._percentLbl.setText(str(value) + "%")
@Slot()
def _onSpeedChange(self, value):
'''
Invoked every time one of the speed setting radio buttons are selected.
Resets the algorithm iterating callback timer if it's currently running.
'''
self._spdSetting = self._speedGroup.checkedId()
if self._timer.isActive():
self._resetTimer()
@Slot()
def _onSetup(self):
'''
Invoked when the setup button is pushed. Re-initializes the world model
and the algorithm.
'''
self._timer.stop()
self._runBtn.setText('Run')
self._model.reset(self._percentObstacleSldr.value() / 100.0)
self._alg.reset()
self._doneLbl.setText("No")
self._solvableLbl.setText("Yes")
self._doneLbl.setAutoFillBackground(False)
self._solvableLbl.setAutoFillBackground(False)
self._worldWidget.repaint()
@Slot()
def _onRun(self):
'''
Invoked when the run button is pushed. Toggles the algorithm iterating
timer on and off.
'''
if self._timer.isActive():
self._timer.stop()
self._runBtn.setText("Run")
else:
self._resetTimer()
self._runBtn.setText("Stop")
@Slot()
示例8: SpiderTab
# 需要导入模块: from PySide.QtCore import QTimer [as 别名]
# 或者: from PySide.QtCore.QTimer import isActive [as 别名]
class SpiderTab(QWidget):
"""Has handlers for spider data and events. It houses the results table of the
spider, controls for the spider and progress indication
It implicitly conforms to IEventHandler interface"""
TIMER_CHECK_INTERVAL = 3000
favicon_received = Signal(str) # send the url or path to the handler, which should be the tab widget
stop_spider_signal = Signal(int)
became_current = Signal(bool) # tell the table it has become active. it's an interesting property for producers!
def __init__(self, parent=None, **kwargs):
super(SpiderTab, self).__init__(parent)
self._event_queue = None
self._data_queue = None
self._engine = None
self._favicon_received = False
self._spider_id = None
self._item_count = 0
self.setContextMenuPolicy(Qt.ContextMenuPolicy.DefaultContextMenu)
self.initInterface(kwargs)
self._context_menu = None
self._setupContextMenu()
self.became_current.connect(self._set_table_activity)
self._queue_check_timer = QTimer()
self._queue_check_timer.setInterval(self.TIMER_CHECK_INTERVAL)
self._queue_check_timer.timeout.connect(self._checkQueues)
self._queue_check_timer.start()
def initInterface(self, kwargs):
layout = QGridLayout()
self._data_table = SearchTable(name=kwargs.get("name"))
self._progress_spider = QProgressBar()
self._label_count = QLabel(self.tr("0 items scraped"))
# make it a busy indicator. you don't know when it'll finish
self._progress_spider.setMinimum(0); self._progress_spider.setMaximum(0)
self._progress_spider.setTextVisible(False)
self._btn_stop_spider = QPushButton(self.tr("Stop Spider"))
self._btn_stop_spider.clicked.connect(self.stop_spider)
row = 0; col = 0;
layout.addWidget(self._data_table, row, col, 1, 4)
row += 1;
layout.addWidget(self._progress_spider, row, col, 1, 1)
col += 1
layout.addWidget(self._label_count, row, col, 1, 2)
col += 2
layout.addWidget(self._btn_stop_spider, row, col, 1, 1)
self.setLayout(layout)
def _setupContextMenu(self):
from visualscrape.lib.data import ActionStore
self._context_menu = QMenu(self)
# get the export action from the action store
action_store = ActionStore.get_instance()
for action in action_store:
if action.get_name() == "export":
export_action = action
break
self._context_menu.addAction(export_action)
def export_table(self):
export_dialog = ExportDialog()
export_dialog.exec_()
export_info = export_dialog.data()
if export_info:
data = self._data_table.get_visible_data()
FileExporter.export(data, self._data_table.name.lower(), export_info.location, export_info.format)
def set_event_queue(self, eq):
self._event_queue = eq
def set_data_queue(self, dq):
self._data_queue = dq
def stop_spider(self):
if self._spider_id is None: # do not stop the the spider before receiving data
pass
else:
if self._queue_check_timer.isActive():
confirm_stop = QMessageBox(self)
confirm_stop.setIcon(QMessageBox.Warning)
confirm_stop.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
confirm_stop.setText(self.tr("Scraping process still running"))
confirm_stop.setDetailedText(self.tr("Are you sure you want to stop it?"))
confirm_stop.setWindowTitle(self.tr("Spider still running"))
ret = confirm_stop.exec_()
if ret == QMessageBox.Yes:
self.stop_spider_signal.emit(self._spider_id)
return True
else: return False # I won't whip you if you stop it accidentally
else: return True # already over
def configure_searchlineedit(self, lineEdit):
self._data_table.configure_search_lineedit(lineEdit)
def _checkQueues(self):
while not self._event_queue.empty():
event = self._event_queue.get(block=False, timeout=0)
if isinstance(event, SpiderClosed):
self._queue_check_timer.stop()
self._progress_spider.setMinimum(0)
self._progress_spider.setMaximum(100)
#.........这里部分代码省略.........
示例9: Navigator
# 需要导入模块: from PySide.QtCore import QTimer [as 别名]
# 或者: from PySide.QtCore.QTimer import isActive [as 别名]
#.........这里部分代码省略.........
return
last_axis = self.crossed_axes[0]
ax = self.getAxis(last_axis)
retry_axis_id = ax.retry_axis
retry_axis = self.getAxis(retry_axis_id)
if retry_axis:
self.logger.info('El axis %s tiene como retry axis a %s lo estarteo' % (ax.id,ax.retry_axis))
self.startSecuence(retry_axis)
def processLoadStarted(self):
inst = Jaime.getInstance()
self.logger.info('Page started load to %s' % inst.view.url().toString())
# print inst.page.mainFrame().requestedUrl()
self.inactivity_timeout.stop()
self.loading_timeout.stop()
self.loading_timeout.start()
self.logger.info('Starting loading timeout and stopping inactivity timeout')
self.last_url = inst.view.url()
def loadingTimeoutAction(self):
self.logger.warning('Loading timeout fired')
inst = Jaime.getInstance()
if (not inst.view.url().isEmpty() and re.match('http.?://',inst.view.url().toString()) ) \
and not self.page_reloads:
self.logger.info('Timeout fired, reloading last url %s' % inst.view.url().toString())
self.page_reloads += 1
self.loading_timeout.stop()
inst.view.reload()
else:
self.logger.error("""Timeout fired, clossing jaime, there isn't last_url or max_reloads reatched""" )
inst.finishWork()
def processPageLoadFinished(self,status):
inst = Jaime.getInstance()
self.logger.info('Page finished load to %s with status %s ' % (inst.view.url().toString(),
status))
if status:
self.current_url = inst.view.url()
self.loading_timeout.stop()
self.page_reloads = 0
self.logger.info('Stopping loading timeout')
else:
self.current_url = QUrl()
self.testJumpRules(self.JUMP_SIGNAL_PAGE_LOAD_FINISH,
status)
def testJumpRules(self,signal,*args):
# self.logger.info('Call to restJumpRules with signal %s' % signal)
# print 'Call to restJumpRules %s' % ( signal)
if signal == self.JUMP_SIGNAL_PAGE_LOAD_FINISH:
print 'llamo a crosed axis'
self.pushCrossedAxis()
elif signal == self.JUMP_SIGNAL_REQUEST_LOAD_FINISH:
if not self.current_axis_id:
return
req_headers = args[0]
rep_headers = args[1]
ax = self.getAxis(self.current_axis_id)
# print '%s tiene exit_method %s' % (ax,ax.axis_exit_method)
if ax.axis_exit_method and \
ax.axis_exit_method == RouteAxis.CROSS_AXIS_METHOD_AJAX:
if 'X-Requested-With' in req_headers:
if ax.axis_exit_method_toggled :
ax.axis_exit_method = ax.axis_exit_method_toggled
ax.axis_exit_method_toggled = None
self.pushCrossedAxis(True)
def pushCrossedAxis(self,*params):
if self.cross_axis_delay.isActive() or \
self.cross_axis_params is not None:
self.logger.warning("""Can't push crossAxis call, there is another call in process""")
return
self.cross_axis_params = params
ax = self.getAxis(self.current_axis_id)
if ax and ax.delay_node_test:
delay = ax.delay_node_test
else:
delay = None
if delay:
self.cross_axis_delay.setInterval(delay)
self.cross_axis_delay.start()
self.logger.info('Delaying %s seconds crossedAxis call ' % int( int(delay) /1000) )
else:
self.crossedAxis()
示例10: Quiz
# 需要导入模块: from PySide.QtCore import QTimer [as 别名]
# 或者: from PySide.QtCore.QTimer import isActive [as 别名]
#.........这里部分代码省略.........
elif self.pauseAction.text() == '&Start quiz!':
self.waitUntilNextTimeslot()
self.pauseAction.setText('&Pause')
self.pauseAction.setShortcut('P')
self.trayIcon.setToolTip('Quiz in progress!')
self.trayIcon.setIcon(QIcon(PATH_TO_RES + TRAY + 'active.png'))
else:
self.waitUntilNextTimeslot()
self.pauseAction.setText('&Pause')
self.pauseAction.setShortcut('P')
self.trayIcon.setToolTip('Quiz in progress!')
self.trayIcon.setIcon(QIcon(PATH_TO_RES + TRAY + 'active.png'))
self.stats.pauseEnded()
#self.updater.mayUpdate = False
else:
self.showSessionMessage(u'Sorry, cannot pause while quiz in progress!')
def showQuiz(self):
if self.isHidden():
self.updateContent()
self.setButtonsActions()
self.show()
self.setWindowOpacity(0)
self.fade()
self.countdown.setValue(self.options.getCountdownInterval() * 100)
self.beginCountdown()
self.stats.musingsStarted()
if self.nextQuizTimer.isActive(): self.nextQuizTimer.stop()
#self.updater.mayUpdate = False
else:
self.showSessionMessage(u'Quiz is already underway!')
def showOptions(self):
self.optionsDialog.show()
def showAbout(self):
self.about.show()
def showQuickDict(self):
self.qdict.showQDict = True
def showGlobalStatistics(self):
print '...'
def startTrayLoading(self):
self.gifLoading.start()
#self.iconTimer = QTimer()
#self.iconTimer.timeout.connect(self.updateTrayIcon)
#self.iconTimer.start(100)
def stopTrayLoading(self):
self.gifLoading.stop()
def updateTrayIcon(self):
self.trayIcon.setIcon(self.gifLoading.currentPixmap())
def showSessionMessage(self, message):
"""Shows info message"""
self.status.message.setText(message)
self.status.show()
示例11: start_GUI
# 需要导入模块: from PySide.QtCore import QTimer [as 别名]
# 或者: from PySide.QtCore.QTimer import isActive [as 别名]
#.........这里部分代码省略.........
#close previous file and open a new one
self.savefile.close()
try:
#write buffer to disk every 256 bytes of data (0.25 Ko)
self.savefile=open(data,'a',256)
except:
try:
#save data even if the savefile could not be created (the name of which was provided by the user)
self.savefile=open("Unsaved-data-"+time.strftime("%a-%d-%b-%Y-%H-%M-%S-UTC", time.gmtime())+".txt",'a',256)
except:
self.savefile=open("Savefile_of_last_resort",'a',256)
elif note==True:
#if note==True, "data" is actually a header for the incoming data
######initialize data storage######
self.current_header=data
#set-up empty data lists
self.measdata=[ [] for i in range(len(data))]
#######Store header to file#######
self.savefile.write("\t".join(data)+'\n')
else:
#good data incoming (hopefully)
#######Store data to file#########
self.savefile.write('\t'.join(map(str,data))+'\n')
#######Update Master data list####
for i in range(len(data)):
self.measdata[i].append(data[i])
self.data_queue.task_done()
self.save_data_timer.start(100)
def switch_measurements_state(self):
if self.measurements_thread.isAlive():
self.stop_measurements()
else:
self.start_measurements()
def start_measurements(self):
#fetch the values from the frontpanel
self.frontpanel_values=Frontpanel_values(self.ui)
#print "Frontpanel loaded"
#fetch the measurement type
meas_thread_class=self.meas_thread_list[self.ui.measMode.currentIndex()]
#print "Measurements prog loaded"
######initialize savefile######
#it could be done in 'save_data' function, but then you mustn't access
#self.frontpanel, because the measurement thread has started, so just do it before starting the measurement thread
#256 is the buffer size in bytes, 'a' is for 'append', in order to ensure never to erase any file
self.savefile=open(self.frontpanel_values.savefile_txt_input,'a',256)
#initiate a thread to run the measurements without freezing the frontpanel
#print "launching meas prog"
self.measurements_thread=meas_thread_class(self,
self.frontpanel_values,
self.data_queue,
self.measurements_thread_stop_flag,
self.reserved_access_to_instr)
#self.instr_IO.connected_instr) for next upgrade
#change the text on the button
self.ui.pushButton.setText("Stop\nMeasurements")
#start the measurements thread, which will run independently from the main thread
self.measurements_thread.start()
print "Measurements started"
#start the timer that periodically saves the data
self.save_data_timer.start(100)
#initialize a QTimer to check measurement thread activity
#and do the clean up when the measurement thread stops
self.check_thread_activity = QTimer()
self.check_thread_activity.timeout.connect(self.check_measurements)
self.check_thread_activity.start(200)
def check_measurements(self):
if not(self.measurements_thread.isAlive()):
self.stop_measurements()
def stop_measurements(self):
self.check_thread_activity.stop()
if self.measurements_thread.isAlive():
print "Stopping Measurements Thread"
#tell the measurements thread to stop by setting this flag
#(this flag is thread safe: it can't be access by both threads at the same time)
self.measurements_thread_stop_flag.set()
#wait for the thread to finish safely (it can take a while if the measurement program has few stopping points set up)
self.measurements_thread.join()
print "Measurements Thread Stopped"
#reset the flag
self.measurements_thread_stop_flag.clear()
#stop the timer that saves data
if self.save_data_timer.isActive():
#abort the waiting time and immediateley finish saving data
self.save_data_timer.stop()
self.save_data()
#previous line will relaunch the timer so stop it again
self.save_data_timer.stop()
self.savefile.close()
#change the text on the button
self.ui.pushButton.setText("Start\nMeasurements")
def savefile_txt_input_open(self):
fileName = QFileDialog.getSaveFileName(self,"Savefile",dir= "./measurements data")
#if the user chooses 'Cancel' in the dialog, a unicode empty string is returned
if not(fileName[0]==u''):
self.ui.savefile_txt_input.setText(fileName[0])
示例12: MyMainWindow
# 需要导入模块: from PySide.QtCore import QTimer [as 别名]
# 或者: from PySide.QtCore.QTimer import isActive [as 别名]
class MyMainWindow(QtGui.QMainWindow):
def __init__(self, frequency, parent=None):
super(MyMainWindow, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
wd = os.path.dirname(os.path.abspath(__file__))
self.tick_pixmaps = {True: QtGui.QPixmap(os.path.join(wd, 'pics', 'blinkenlicht_on.png')),
False: QtGui.QPixmap(os.path.join(wd, 'pics', 'blinkenlicht_off.png'))}
self.speaker_pixmaps = {True: QtGui.QIcon(QtGui.QPixmap(os.path.join(wd, 'pics', 'speaker_on.png'))),
False: QtGui.QIcon(QtGui.QPixmap(os.path.join(wd, 'pics', 'speaker_off.png')))}
self.tick_soundFile=QFile()
self.tick_soundFile.setFileName(os.path.join(wd, 'sounds', 'tick.raw'))
self.tick_soundFile.open(QIODevice.ReadOnly)
self.play_sound = True
self.format = QAudioFormat()
self.format.setChannels(1)
self.format.setFrequency(44050)
self.format.setSampleSize(16)
self.format.setCodec("audio/pcm")
self.format.setByteOrder(QAudioFormat.LittleEndian)
self.format.setSampleType(QAudioFormat.SignedInt)
self.audio_output = QAudioOutput(self.format)
self.ui.ping_icon.setPixmap(self.tick_pixmaps[False])
self.ui.speaker_button.setIcon(self.speaker_pixmaps[self.play_sound])
self.blink_timer = QTimer()
self.blink_timer.setSingleShot(True)
self.blink_timer.timeout.connect(self.clear_blink)
self.timer = QTimer()
self.frequency = frequency
self.last_played = 0
self.count = 0
self.ui.f_spin.setValue(self.frequency)
self.set_speed()
self.timer.timeout.connect(self.play_tick)
self.play_ctrl = {True: 'Stop',
False: 'Start'}
self.ui.play_button.setText(self.play_ctrl[False])
self.ui.statusBar.showMessage('{count:04d} - Dev.: {delta:.3f} ms'.format(delta=0, count=self.count))
def set_frequency(self, frequency):
self.frequency = frequency
self.set_speed()
self.last_played = 0
self.count = 0
def set_speed(self):
self.speed = 1000.0 / (self.frequency / 60.0)
self.timer.setInterval(self.speed)
def clear_blink(self):
self.ui.ping_icon.setPixmap(self.tick_pixmaps[False])
def toggle_play(self):
if self.timer.isActive():
self.timer.stop()
self.last_played = 0
self.count = 0
self.ui.statusBar.clearMessage()
else:
self.timer.start(self.speed)
self.play_tick()
self.ui.play_button.setText(self.play_ctrl[self.timer.isActive()])
def toggle_play_sound(self):
if self.play_sound:
self.play_sound = False
self.audio_output.stop()
else:
self.play_sound = True
self.ui.speaker_button.setIcon(self.speaker_pixmaps[self.play_sound])
def play_tick(self):
if self.last_played:
delta = ((time.time() - self.last_played) * 1000.0) - self.speed
else:
delta = 0
self.last_played = time.time()
self.audio_output.stop()
self.audio_output.reset()
if self.play_sound:
self.tick_soundFile.seek(0)
self.audio_output.start(self.tick_soundFile)
self.count += 1
self.ui.statusBar.showMessage('{count:04d} - Dev.: {delta:.3f} ms'.format(delta=delta, count=self.count))
#.........这里部分代码省略.........
示例13: Panel
# 需要导入模块: from PySide.QtCore import QTimer [as 别名]
# 或者: from PySide.QtCore.QTimer import isActive [as 别名]
class Panel(QWidget):
def __init__(self,parent=None,instr=None,lock=None,title='Instrument Panel'):
# This class derivates from a Qt Widget so we have to call
# the class builder ".__init__()"
QWidget.__init__(self)
# "self" is now a Qt Widget, then we load the user interface
# generated with QtDesigner and call it self.ui
self.ui = SR830_Ui.Ui_Panel()
# Now we have to feed the GUI building method of this object (self.ui)
# with the current Qt Widget 'self', but the widgets from the design will actually be built as children
# of the object self.ui
self.ui.setupUi(self)
self.setWindowTitle(title)
self.reserved_access_to_instr=lock
self.instr=instr
self.monitor_timer = QTimer()
self.channel=self.ui.channel.currentIndex()
#The timer would not wait for the completion of the task otherwise
self.monitor_timer.setSingleShot(True)
self.monitor_timer.timeout.connect(self.monitor)
self.firsttime=0
#bug: if the box is checked in the .ui file, the system freezes
#if self.ui.monitor.isChecked():self.monitor()
def update_boxes(self):
with self.reserved_access_to_instr:
#There are two signals emitted if the current item of a combobox changes,
#PySide.QtGui.QComboBox.currentIndexChanged() and PySide.QtGui.QComboBox.activated().
#PySide.QtGui.QComboBox.currentIndexChanged() is always emitted regardless
#if the change was done programmatically or by user interaction,
#while PySide.QtGui.QComboBox.activated() is only emitted when the change is caused by user interaction.
self.ui.sense.setCurrentIndex(self.instr.query_sensitivity())
self.ui.TC.setCurrentIndex(self.instr.query_time_cste())
self.ui.filter.setCurrentIndex(self.instr.query_filter_slop())
self.ui.channel.setCurrentIndex(self.instr.query_ch1_display())
self.ch1=self.ui.channel.currentText()
self.ui.channel_2.setCurrentIndex(self.instr.query_ch2_display())
self.ch2=self.ui.channel_2.currentText()
self.ui.ref_source.setCurrentIndex(self.instr.query_ref_mode())
def monitor(self,state=1):
if state!=1:
self.monitor_timer.stop()
self.firsttime=0
elif state and not(self.monitor_timer.isActive()):
self.firsttime+=1
if self.firsttime==1:self.update_boxes()
with self.reserved_access_to_instr:
x,y=self.instr.query_ch1_ch2(self.ch1,self.ch2)
self.ui.x_disp.setText(str(x))
self.ui.y_disp.setText(str(y))
self.ui.f_disp.setText(str(self.instr.query_frequency())+' Hz')
self.ui.a_disp.setText(str(self.instr.query_amplitude())+' V')
self.ui.ph_disp.setText(str(self.instr.query_phase())+' deg')
self.monitor_timer.start(self.ui.refresh_rate.value()*1000)
def update_timer_timeout(self,secs):
#The value must be converted to milliseconds
self.monitor_timer.setInterval(secs*1000)
def change_f(self,value=0):
with self.reserved_access_to_instr:
self.instr.set_frequency(value)
def change_A(self,value=0):
with self.reserved_access_to_instr:
self.instr.set_amplitude(value)
def change_ph(self,value=0):
with self.reserved_access_to_instr:
self.instr.set_amplitude(value)
def change_x(self,value):
with self.reserved_access_to_instr:
self.instr.set_ch1_display(value)
self.ch1=value#self.instr.query_ch1_display()
def change_y(self,value):
with self.reserved_access_to_instr:
self.instr.set_ch2_display(value)
self.ch2=value#self.instr.query_ch2_display()
def change_s(self,value=0):
with self.reserved_access_to_instr:
self.instr.set_sensitivity(value)
def change_TC(self,value=0):
with self.reserved_access_to_instr:
self.instr.set_time_cste(value)
def change_filter(self,value=0):
with self.reserved_access_to_instr:
self.instr.set_filter_slop(value)
def change_ref(self,value='Internal'):
with self.reserved_access_to_instr:
self.instr.set_ref_mode(value)