本文整理汇总了Python中PyQt4.QtCore.QTime.start方法的典型用法代码示例。如果您正苦于以下问题:Python QTime.start方法的具体用法?Python QTime.start怎么用?Python QTime.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtCore.QTime
的用法示例。
在下文中一共展示了QTime.start方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from PyQt4.QtCore import QTime [as 别名]
# 或者: from PyQt4.QtCore.QTime import start [as 别名]
def __init__(self, db, sql, parent=None):
self.db = db.connector
t = QTime()
t.start()
c = self.db._execute(None, unicode(sql))
self._secs = t.elapsed() / 1000.0
del t
self._affectedRows = 0
data = []
header = self.db._get_cursor_columns(c)
if header is None:
header = []
try:
if len(header) > 0:
data = self.db._fetchall(c)
self._affectedRows = c.rowcount
except DbError:
# nothing to fetch!
data = []
header = []
BaseTableModel.__init__(self, header, data, parent)
# commit before closing the cursor to make sure that the changes are stored
self.db._commit()
c.close()
del c
示例2: run
# 需要导入模块: from PyQt4.QtCore import QTime [as 别名]
# 或者: from PyQt4.QtCore.QTime import start [as 别名]
def run(self):
time = QTime()
eventLoop = QEventLoop()
self.m_bStop = False
# log.debug("Запускаем поток")
#if not self.initThread():
#return
while not self.m_bStop:
self.m_nTactCounter += 1 # Добавить обнуление при переполнении
time.start()
eventLoop.processEvents()
if not self.workThread():
self.m_bStop = True
return
workTime = time.elapsed()
if 0 <= workTime < self.m_nTact:
self.msleep(self.m_nTact - workTime)
else:
self.msleep(0)
eventLoop.processEvents()
self.exitThread()
示例3: AutoSaver
# 需要导入模块: from PyQt4.QtCore import QTime [as 别名]
# 或者: from PyQt4.QtCore.QTime import start [as 别名]
class AutoSaver(QObject):
"""
Class implementing the auto saver.
"""
AUTOSAVE_IN = 1000 * 3
MAXWAIT = 1000 * 15
def __init__(self, parent, save):
"""
Constructor
@param parent reference to the parent object (QObject)
@param save slot to be called to perform the save operation
"""
QObject.__init__(self, parent)
if parent is None:
raise RuntimeError("AutoSaver: parent must not be None.")
self.__save = save
self.__timer = QBasicTimer()
self.__firstChange = QTime()
def changeOccurred(self):
"""
Public slot handling a change.
"""
if self.__firstChange.isNull():
self.__firstChange.start()
if self.__firstChange.elapsed() > self.MAXWAIT:
self.saveIfNeccessary()
else:
self.__timer.start(self.AUTOSAVE_IN, self)
def timerEvent(self, evt):
"""
Protected method handling timer events.
@param evt reference to the timer event (QTimerEvent)
"""
if evt.timerId() == self.__timer.timerId():
self.saveIfNeccessary()
else:
QObject.timerEvent(self, evt)
def saveIfNeccessary(self):
"""
Public method to activate the save operation.
"""
if not self.__timer.isActive():
return
self.__timer.stop()
self.__firstChange = QTime()
self.__save()
示例4: OpenAnt
# 需要导入模块: from PyQt4.QtCore import QTime [as 别名]
# 或者: from PyQt4.QtCore.QTime import start [as 别名]
class OpenAnt(QApplication):
def __init__(self):
QApplication.__init__(self, sys.argv)
# Set the default background color to a darker grey.
self.setPalette(QPalette(self.palette().button().color(), QColor(192, 192, 192)))
self.window = MainWindow()
self.window.show()
self.window.start()
self.window.setWindowTitle('OpenAnt')
# Game timer, used in the gameloop FPS calculations.
self.game_timer = QTime()
self.game_timer.start()
# Draw map, set view to ground.
self.map = Map()
Globals.view = self.map.generateMap()
self.map.spawnAnts()
# Start the main loop.
self.gameLoop()
def gameLoop(self):
TICKS_PER_SECOND = 20
SKIP_TICKS = 1000 / TICKS_PER_SECOND
MAX_FRAMESKIP = 5
next_game_tick = self.getTickCount()
Globals.game_is_running = True
while Globals.game_is_running:
loops = 0
while self.getTickCount() > next_game_tick and loops < MAX_FRAMESKIP:
self.updateGame()
next_game_tick += SKIP_TICKS
loops += 1
interpolation = float(self.getTickCount() + SKIP_TICKS - next_game_tick) / float(SKIP_TICKS)
self.updateDisplay(interpolation)
def updateDisplay(self, interpolation):
#lerp away
if not 'nolerp' in sys.argv:
if self.map.yellowAnt.moving:
self.map.yellowAnt.lerpMoveSimple(interpolation)
Globals.glwidget.updateGL()
self.processEvents() # Let Qt process its events.
def getTickCount(self):
return self.game_timer.elapsed()
def updateGame(self):
self.map.update()
示例5: __init__
# 需要导入模块: from PyQt4.QtCore import QTime [as 别名]
# 或者: from PyQt4.QtCore.QTime import start [as 别名]
def __init__(self, db, sql, parent=None):
# create a virtual layer with non-geometry results
q = QUrl.toPercentEncoding(sql)
t = QTime()
t.start()
tf = QTemporaryFile()
tf.open()
tmp = tf.fileName()
tf.close()
p = QgsVectorLayer("%s?query=%s" % (QUrl.fromLocalFile(tmp).toString(), q), "vv", "virtual")
self._secs = t.elapsed() / 1000.0
if not p.isValid():
data = []
header = []
raise DbError(p.dataProvider().error().summary(), sql)
else:
header = [f.name() for f in p.fields()]
has_geometry = False
if p.geometryType() != QGis.WKBNoGeometry:
gn = getQueryGeometryName(tmp)
if gn:
has_geometry = True
header += [gn]
data = []
for f in p.getFeatures():
a = f.attributes()
if has_geometry:
if f.geometry():
a += [f.geometry().exportToWkt()]
else:
a += [None]
data += [a]
self._secs = 0
self._affectedRows = len(data)
BaseTableModel.__init__(self, header, data, parent)
示例6: __evaluate
# 需要导入模块: from PyQt4.QtCore import QTime [as 别名]
# 或者: from PyQt4.QtCore.QTime import start [as 别名]
def __evaluate(self, query):
"""
:type query: str
:return: bool
"""
t = QTime()
t.start()
qDebug("\n(VFK) SQL: {}\n".format(query))
self.setQuery(query, QSqlDatabase.database(self.__mConnectionName))
while self.canFetchMore():
self.fetchMore()
if t.elapsed() > 500:
qDebug("\n(VFK) Time elapsed: {} ms\n".format(t.elapsed()))
if self.lastError().isValid():
qDebug('\n(VFK) SQL ERROR: {}'.format(self.lastError().text()))
return False
return True
示例7: importALKIS
# 需要导入模块: from PyQt4.QtCore import QTime [as 别名]
# 或者: from PyQt4.QtCore.QTime import start [as 别名]
def importALKIS(self):
if os.environ.has_key('CPL_DEBUG'):
self.log( u"Debug-Ausgaben aktiv." )
files = []
for i in range(self.lstFiles.count()):
files.append( self.lstFiles.item(i).text() )
s = QSettings( "norBIT", "norGIS-ALKIS-Import" )
s.setValue( "service", self.leSERVICE.text() )
s.setValue( "host", self.leHOST.text() )
s.setValue( "port", self.lePORT.text() )
s.setValue( "dbname", self.leDBNAME.text() )
s.setValue( "uid", self.leUID.text() )
s.setValue( "pwd", self.lePWD.text() )
s.setValue( "gt", self.leGT.text() )
s.setValue( "files", files )
s.setValue( "skipfailures", self.cbxSkipFailures.isChecked()==True )
s.setValue( "usecopy", self.cbxUseCopy.isChecked()==True )
self.fnbruch = self.cbFnbruch.currentIndex()==0
s.setValue( "fnbruch", self.fnbruch )
self.epsg = int( self.cbEPSG.itemData( self.cbEPSG.currentIndex() ) )
s.setValue( "epsg", self.epsg)
self.running = True
self.canceled = False
self.pbStart.setText( "Abbruch" )
self.pbStart.clicked.disconnect(self.run)
self.pbStart.clicked.connect(self.cancel)
self.pbAdd.setDisabled(True)
self.pbAddDir.setDisabled(True)
self.pbRemove.setDisabled(True)
self.pbLoad.setDisabled(True)
self.pbSave.setDisabled(True)
self.lstFiles.itemSelectionChanged.disconnect(self.selChanged)
QApplication.setOverrideCursor( Qt.WaitCursor )
while True:
t0 = QTime()
t0.start()
self.loadRe()
self.lstFiles.clearSelection()
conn = self.connectDb()
if conn is None:
break
self.log( "Import-Version: 7f82ac2" )
self.db.exec_( "SET application_name='ALKIS-Import - Frontend'" )
self.db.exec_( "SET client_min_messages TO notice" )
qry = self.db.exec_( "SELECT version()" )
if not qry or not qry.next():
self.log(u"Konnte PostgreSQL-Version nicht bestimmen!")
break
self.log( "Datenbank-Version: %s" % qry.value(0) )
m = re.search( "PostgreSQL (\d+)\.(\d+)", qry.value(0) )
if not m:
self.log(u"PostgreSQL-Version nicht im erwarteten Format")
break
if int(m.group(1)) < 8 or ( int(m.group(1))==8 and int(m.group(2))<3 ):
self.log(u"Mindestens PostgreSQL 8.3 erforderlich")
break
qry = self.db.exec_( "SELECT postgis_version()" )
if not qry or not qry.next():
self.log(u"Konnte PostGIS-Version nicht bestimmen!")
break
self.log( "PostGIS-Version: %s" % qry.value(0) )
qry = self.db.exec_( "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public' AND table_name='alkis_importlog'" )
if not qry or not qry.next():
self.log( u"Konnte Existenz von Protokolltabelle nicht überprüfen." )
break
if int( qry.value(0) ) == 0:
qry = self.db.exec_( "CREATE TABLE alkis_importlog(n SERIAL PRIMARY KEY, ts timestamp default now(), msg text)" )
if not qry:
self.log( u"Konnte Protokolltabelle nicht anlegen [%s]" % qry.lastError().text() )
break
elif self.cbxClearProtocol.isChecked():
qry = self.db.exec_( "TRUNCATE alkis_importlog" )
if not qry:
self.log( u"Konnte Protokolltabelle nicht leeren [%s]" % qry.lastError().text() )
break
self.cbxClearProtocol.setChecked( False )
#.........这里部分代码省略.........
示例8: Window
# 需要导入模块: from PyQt4.QtCore import QTime [as 别名]
# 或者: from PyQt4.QtCore.QTime import start [as 别名]
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window,self).__init__()
self.setGeometry(50,50,500,300)
self.setWindowTitle("Respiratory analysis")
self.ser=serial.Serial('COM35',4800)
self.menu()
self.home()
def menu(self):
#--------------------Complete Menus------------------
mainMenu=self.menuBar()
mainMenu.setStatusTip('Select Options from main menu')
fileMenu=mainMenu.addMenu('&File')
fileMenu.setStatusTip('Select Options from File Menu')
windowMenu=mainMenu.addMenu('&Plot')
windowMenu.setStatusTip('Select Options from Window Menu')
connectionMenu=mainMenu.addMenu('&Connection')
connectionMenu.setStatusTip('Select Options from Connection Menu')
helpMenu=mainMenu.addMenu('&Help')
helpMenu.setStatusTip('Select for help')
#----------------File Menus--------------------------------------
#--------------Exit Action---------------------------------------
exitAction=QtGui.QAction("&Exit",self)
exitAction.setShortcut("Ctrl + Q")
exitAction.setStatusTip("Leave the Application")
exitAction.triggered.connect(self.close_application)
fileMenu.addAction(exitAction)
#---------------------------------------------------
#----------------------------------------------------------------
#-----------------Plot Menus-----------------------------------
#----------------------------------------------------------------
zoomin=QtGui.QAction('&Zoom In',self)
zoomin.setStatusTip("Click to Zoom In")
zoomin.setShortcut("Ctrl + =")
zoomin.triggered.connect(self.zoom_in)
windowMenu.addAction(zoomin)
zoomout=QtGui.QAction('&Zoom Out',self)
zoomout.setStatusTip("Click to Zoom Out")
zoomout.setShortcut("Ctrl + -")
zoomout.triggered.connect(self.zoom_out)
windowMenu.addAction(zoomout)
#----------------------------------------------------------------
#----------------------------------------------------------------
#----------------Connection Menus--------------------------------
#----------------COM Ports---------------------------------------
comMenu=connectionMenu.addMenu('&COM Ports')
com=list(serial.tools.list_ports.comports())
for i in range(len(com)):
comAction=QtGui.QAction('&'+com[i][0],self)
comAction.setStatusTip("Click to connect to "+com[i][0]+" Port")
comAction.triggered.connect(self.establish_conn)
comMenu.addAction(comAction)
self.statusBar()
def establish_conn(self,name):
print(name)
def zoom_in(self):
self.ylow=self.ylow+100
self.yhigh=self.yhigh-100
self.p1.setYRange(self.ylow,self.yhigh)
def zoom_out(self):
self.ylow=self.ylow-100
self.yhigh=self.yhigh+100
self.p1.setYRange(self.ylow,self.yhigh)
def home(self):
self.splitter1=QtGui.QSplitter(Qt.Vertical,self)
self.splitter2=QtGui.QSplitter(Qt.Vertical,self)
self.wid=QtGui.QWidget()
self.setCentralWidget(self.wid)
self.hbox=QtGui.QHBoxLayout()
self.vbox=QtGui.QVBoxLayout()
self.wid.setLayout(self.hbox)
self.hbox.addLayout(self.vbox)
self.resize(1000,800)
self.data1=deque(maxlen=1000)
self.data=[]
self.t=QTime()
self.t.start()
self.timer1=QtCore.QTimer()
self.timer1.timeout.connect(self.update)
self.timer2=QtCore.QTimer()
self.timer2.timeout.connect(self.read_data)
self.timer3=QtCore.QTimer()
self.timer3.timeout.connect(self.stats)
for i in range(2000):
self.data1.append({'x':self.t.elapsed(),'y': 0})
#----------------Left pane--------------------------
#----------------Adding Plot------------------------
self.p1=pg.PlotWidget(name="Raw",title="Respiration Plot",labels={'left':("Thoracic Circumference in (cm)"),'bottom':("Time Elapsed (mm:ss)")},enableMenu=True,axisItems={'bottom': TimeAxisItem(orientation='bottom')})
self.p1.addLegend(offset=(450,30))
self.p1.showGrid(x=True,y=True,alpha=0.5)
self.p1.setMouseEnabled(x=True,y=True)
self.curve=self.p1.plot(pen='y',name="Raw Respiration Data")
self.curve1=self.p1.plot(pen='r',name="Filtered Respiration DAta")
self.ylow=600
self.yhigh=800
self.p1.setYRange(self.ylow,self.yhigh)
#----------------------------------------------------
self.statistics=QtGui.QGroupBox()
self.statistics.setTitle("Statistics")
self.stlabel1=QtGui.QLabel("Mean Value\t\t\t:",self.statistics)
#.........这里部分代码省略.........
示例9: PollingKeyboardMonitor
# 需要导入模块: from PyQt4.QtCore import QTime [as 别名]
# 或者: from PyQt4.QtCore.QTime import start [as 别名]
class PollingKeyboardMonitor(AbstractKeyboardMonitor):
"""
Monitor the keyboard for state changes by constantly polling the keyboard.
"""
#: default polling interval
DEFAULT_POLLDELAY = 200
#: size of the X11 keymap array
_KEYMAP_SIZE = 32
def __init__(self, parent=None):
AbstractKeyboardMonitor.__init__(self, parent)
self._keyboard_was_active = False
self._old_keymap = array(b'B', b'\0' * 32)
self._keyboard_timer = QTimer(self)
self._keyboard_timer.timeout.connect(self._check_keyboard_activity)
self._keyboard_timer.setInterval(self.DEFAULT_POLLDELAY)
self._activity = QTime()
self._keys_to_ignore = self.IGNORE_NO_KEYS
self._keymap_mask = self._setup_mask()
self._idle_time = self.DEFAULT_IDLETIME
@property
def is_running(self):
return self._keyboard_timer.isActive()
def start(self):
self._keyboard_timer.start()
self.started.emit()
def stop(self):
AbstractKeyboardMonitor.stop(self)
self._keyboard_timer.stop()
self.stopped.emit()
@property
def keys_to_ignore(self):
return self._keys_to_ignore
@keys_to_ignore.setter
def keys_to_ignore(self, value):
if not (self.IGNORE_NO_KEYS <= value <= self.IGNORE_MODIFIER_COMBOS):
raise ValueError('unknown constant for keys_to_ignore')
self._keys_to_ignore = value
self._keymap_mask = self._setup_mask()
@property
def idle_time(self):
return self._idle_time / 1000
@idle_time.setter
def idle_time(self, value):
self._idle_time = int(value * 1000)
def _setup_mask(self):
mask = array(b'B', b'\xff' * 32)
if self._keys_to_ignore >= self.IGNORE_MODIFIER_KEYS:
modifier_mappings = xlib.get_modifier_mapping(self.display)
for modifier_keys in modifier_mappings:
for keycode in modifier_keys:
mask[keycode // 8] &= ~(1 << (keycode % 8))
return mask
@property
def keyboard_active(self):
is_active = False
_, raw_keymap = xlib.query_keymap(self.display)
keymap = array(b'B', raw_keymap)
is_active = keymap != self._old_keymap
for new_state, old_state, mask in izip(keymap, self._old_keymap,
self._keymap_mask):
is_active = new_state & ~old_state & mask
if is_active:
break
if self._keys_to_ignore == self.IGNORE_MODIFIER_COMBOS:
for state, mask in izip(keymap, self._keymap_mask):
if state & ~mask:
is_active = False
break
self._old_keymap = keymap
return is_active
def _check_keyboard_activity(self):
if self.keyboard_active:
self._activity.start()
if not self._keyboard_was_active:
self._keyboard_was_active = True
self.typingStarted.emit()
elif self._activity.elapsed() > self._idle_time and \
self._keyboard_was_active:
self._keyboard_was_active = False
self.typingStopped.emit()
示例10: Game
# 需要导入模块: from PyQt4.QtCore import QTime [as 别名]
# 或者: from PyQt4.QtCore.QTime import start [as 别名]
#.........这里部分代码省略.........
# Manage Game Progression
self.story = Story(self.FRAME_RATE)
# Manage World
self.places = Places()
def new(self):
"""Load new game from file"""
debug("newgame...loading clues")
self.story.loadClues()
debug("newgame...loading charcter")
self.character = Character((0,0), "Character", "Character")
debug("newgame...loading places")
self.places.loadLoc()
debug("end of load")
self.places.addLoc(self.character)
self.story.currClue = self.story._clueList.pop()
#self.frameTimer = QTimer() # Create Frame Timer
self.gameTime = QTime()
self.launch()
def load(self,filename):
"""Load existing game from file"""
debug("loadgame...read data from saved file")
debug("loadgame...loading clues")
self.story.loadClues()
savedData = open(filename)
nextLine = savedData.readline()
# Parsing saved file
while (nextLine):
line = nextLine.split()
if (len(line) == 4 and self.loadIsValid(line)):
x = int(line[0])
y = int(line[1])
numClues = int(line[2])+1
self.story._clueList = self.story._clueList[:numClues]
self.story.score = int(line[3])
debug("x: " + `x` + " y: " + `y` + " numCLue: " + `len(self.story._clueList)` + \
" score is: " + `int(line[3])`)
nextLine = savedData.readline()
savedData.close()
self.story.currClue = self.story._clueList.pop()
debug("loadgame...loading initial character and places")
self.character = Character((x,y), "Character", "Character")
self.places.loadLoc()
debug("end of load")
self.places.addLoc(self.character)
# FIXME if QTime and QTimer should be stored in certain way
self.gameTime = QTime()
#self.frameTimer = QTimer() # Create Frame Timer
self.launch()
def loadIsValid(self,obj):
"""Check that the input from saved file is valid"""
posx = obj[0]
posy = obj[1]
numClue = obj[2]
score = obj[3]
try:
int(posx) and int(posy) and int(numClue) and int(score)
except:
debug("Invalid position input in save file")
return False
return True
def save(self, filename):
"""Save to file"""
fname = open(filename, "w")
score = `self.story.score`
numClues = `len(self.story._clueList)`
charX, charY = self.character.getCenter()
toWriteList = '\t' + `charX` + '\t' + `charY` + '\t' + \
numClues + '\t' + score
fname.write(toWriteList)
fname.close()
def endGame(self):
"""Make things tidy for another game instance"""
# Signal that we have won the game and should
None
def launch(self):
"""Start sending signals to the game using Timers"""
self.gameTime.start()
self.frameTimer.start(ONE_SECOND/self.FRAME_RATE)
self.frameTimer.timeout.connect(self.story.frameTime)
def keyPress(self, event):
key = event.key()
self.character.keyPress(key)
def keyRelease(self, event):
key = event.key()
self.character.keyRelease(key)
示例11: QTime
# 需要导入模块: from PyQt4.QtCore import QTime [as 别名]
# 或者: from PyQt4.QtCore.QTime import start [as 别名]
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
from PyQt4.QtCore import QTime, QTimer
from collections import deque
t = QTime()
t.start()
data = deque(maxlen=20)
class TimeAxisItem(pg.AxisItem):
def __init__(self, *args, **kwargs):
super(TimeAxisItem, self).__init__(*args, **kwargs)
def tickStrings(self, values, scale, spacing):
# PySide's QTime() initialiser fails miserably and dismisses args/kwargs
return [QTime().addMSecs(value).toString('mm:ss') for value in values]
app = QtGui.QApplication([])
win = pg.GraphicsWindow(title="Basic plotting examples")
win.resize(1000,600)
plot = win.addPlot(title='Timed data', axisItems={'bottom': TimeAxisItem(orientation='bottom')})
curve = plot.plot()
def update():
global plot, curve, data