本文整理汇总了Python中PyQt5.QtCore.QBasicTimer.stop方法的典型用法代码示例。如果您正苦于以下问题:Python QBasicTimer.stop方法的具体用法?Python QBasicTimer.stop怎么用?Python QBasicTimer.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtCore.QBasicTimer
的用法示例。
在下文中一共展示了QBasicTimer.stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Example
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.progress_bar = QProgressBar(self)
self.progress_bar.setGeometry(30, 40, 200, 25)
self.btn = QPushButton('Start', self)
self.btn.move(30, 80)
self.btn.clicked.connect(self.doAction)
self.timer = QBasicTimer()
self.step = 0
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('QProgressBar')
self.show()
def timerEvent(self, QTimerEvent):
if self.step >= 100:
self.timer.stop()
self.btn.setText('Finished')
return
self.step += 1
self.progress_bar.setValue(self.step)
def doAction(self):
if self.timer.isActive():
self.timer.stop()
self.btn.setText('Start')
else:
self.timer.start(100, self)
self.btn.setText('Stop')
示例2: AutoSaver
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [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
@exception RuntimeError raised, if no parent is given
"""
super(AutoSaver, self).__init__(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:
super(AutoSaver, self).timerEvent(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()
示例3: Example
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.pbar = QProgressBar(self)
self.pbar.setGeometry(30, 40, 200, 25)
self.btn = QPushButton('Start', self)
self.btn.move(40, 80)
self.btn.clicked.connect(self.doAction)
# タイマー
self.timer = QBasicTimer()
self.step = 0
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('QProgressBar')
self.show()
def timerEvent(self, e):
# カウントが100に達すると終了
if self.step >= 100:
self.timer.stop()
self.btn.setText('Finished')
return
# 呼ばれるたび1ずつ増やす
self.step = self.step + 1
self.pbar.setValue(self.step)
def doAction(self):
"""ボタンが押されると呼ばれる"""
# タイマーが実行中ならタイマーを停止する
if self.timer.isActive():
self.timer.stop()
self.btn.setText('Start')
# タイマーが停止中ならタイマーを実行する
else:
# (timeout[ms], イベントの受取先)
# timeoutで指定した時間間隔でシグナルが飛ぶ模様
self.timer.start(1000, self)
self.btn.setText('Stop')
示例4: WigglyLabel
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
class WigglyLabel(object):
def __init__(self, clazz):
self.clazz = clazz
# clazz.setBackgroundRole(QPalette.Midlight)
# clazz.setAutoFillBackground(True)
setattr(clazz, "paintEvent", self.paintEvent)
setattr(clazz, "timerEvent", self.timerEvent)
# newFont = self.clazz.font()
# newFont.setPointSize(newFont.pointSize() + 20)
# self.clazz.setFont(newFont)
self.timer = QBasicTimer()
self.step = 0;
self.timer.start(60, self.clazz)
def __del__(self):
self.timer.stop()
def getText(self):
return self.clazz.text()
def paintEvent(self, event):
# 上下跳动
# sineTable = (0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71, -38)
metrics = QFontMetrics(self.clazz.font())
x = (self.clazz.width() - metrics.width(self.getText())) / 2
y = (self.clazz.height() + metrics.ascent() - metrics.descent()) / 2
color = QColor()
painter = QPainter(self.clazz)
for i, ch in enumerate(self.getText()):
index = (self.step + i) % 16
color.setHsv((15 - index) * 16, 255, 191)
painter.setPen(color)
# 上下跳动
# painter.drawText(x, y - ((sineTable[index] * metrics.height()) / 400), ch)
painter.drawText(x, y , ch)
x += metrics.width(ch)
def timerEvent(self, event):
if event.timerId() == self.timer.timerId():
self.step += 1
self.clazz.update()
else:
super(WigglyLabel, self).timerEvent(event)
示例5: MyQt
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
class MyQt(QWidget):
def __init__(self):
super(MyQt, self).__init__()
self.initUI()
def initUI(self):
# 构建一个进度条
self.pbar = QProgressBar(self)
# 从左上角30-50的界面,显示一个200*25的界面
self.pbar.setGeometry(30, 50, 200, 25) # 设置进度条的位置
# 设置开始按钮
self.btn = QPushButton('开始', self)
self.btn.move(50, 90) # 按钮移动的位置
# 点击按钮
# 信号函数不能加括号
self.btn.clicked.connect(self.doAction)
# 构建一个计时器
self.timer = QBasicTimer()
# 计数
self.step = 0
self.setGeometry(300,300,280,170)
self.setWindowTitle('我是进度条')
self.setWindowIcon(QIcon('1.jpg'))
self.show()
def doAction(self):
# 判断是否处于激活状态
if self.timer.isActive():
self.timer.stop()
self.btn.setText('开始')
else:
self.timer.start(100,self)
self.btn.setText('停止')
def timerEvent(self, *args, **kwargs):
if self.step>=100:
# 停止进度条
self.timer.stop()
self.btn.setText('完成')
return
self.step+=1
# 把进度条每次充值的值赋给进图条
self.pbar.setValue(self.step)
示例6: Board
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
class Board(QFrame):
msg2Statusbar = pyqtSignal(str)
BoardWidth = 10
BoardHeight = 22
Speed = 300
def __init__(self, parent):
super().__init__(parent)
self.initBoard()
def initBoard(self):
self.timer = QBasicTimer()
self.isWaitingAfterLine = False
self.curX = 0
self.curY = 0
self.numLinesRemoved = 0
self.board = []
self.setFocusPolicy(Qt.StrongFocus)
self.isStarted = False
self.isPaused = False
self.clearBoard()
def shapeAt(self, x, y):
return self.board[(y * Board.BoardWidth) + x]
def setShapeAt(self, x, y, shape):
self.board[(y * Board.BoardWidth) + x] = shape
def squareWidth(self):
return self.contentsRect().width() // Board.BoardWidth
def squareHeight(self):
return self.contentsRect().height() // Board.BoardHeight
def start(self):
if self.isPaused:
return
self.isStarted = True
self.isWaitingAfterLine = False
self.numLinesRemoved = 0
self.clearBoard()
self.msg2Statusbar.emit(str(self.numLinesRemoved))
self.newPiece()
self.timer.start(Board.Speed, self)
def pause(self):
if not self.isStarted:
return
self.isPaused = not self.isPaused
if self.isPaused:
self.timer.stop()
self.msg2Statusbar.emit("paused")
else:
self.timer.start(Board.Speed, self)
self.msg2Statusbar.emit(str(self.numLinesRemoved))
self.update()
def paintEvent(self, event):
painter = QPainter(self)
rect = self.contentsRect()
boardTop = rect.bottom() - Board.BoardHeight * self.squareHeight()
for i in range(Board.BoardHeight):
for j in range(Board.BoardWidth):
shape = self.shapeAt(j, Board.BoardHeight - i - 1)
if shape != Tetrominoe.NoShape:
self.drawSquare(painter,
rect.left() + j * self.squareWidth(),
boardTop + i * self.squareHeight(), shape)
if self.curPiece.shape() != Tetrominoe.NoShape:
for i in range(4):
#.........这里部分代码省略.........
示例7: TetrixBoard
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
class TetrixBoard(QFrame):
BoardWidth = 10
BoardHeight = 22
scoreChanged = pyqtSignal(int)
levelChanged = pyqtSignal(int)
linesRemovedChanged = pyqtSignal(int)
def __init__(self, parent=None):
super(TetrixBoard, self).__init__(parent)
self.timer = QBasicTimer()
self.nextPieceLabel = None
self.isWaitingAfterLine = False
self.curPiece = TetrixPiece()
self.nextPiece = TetrixPiece()
self.curX = 0
self.curY = 0
self.numLinesRemoved = 0
self.numPiecesDropped = 0
self.score = 0
self.level = 0
self.board = None
self.setFrameStyle(QFrame.Panel | QFrame.Sunken)
self.setFocusPolicy(Qt.StrongFocus)
self.isStarted = False
self.isPaused = False
self.clearBoard()
self.nextPiece.setRandomShape()
def shapeAt(self, x, y):
return self.board[(y * TetrixBoard.BoardWidth) + x]
def setShapeAt(self, x, y, shape):
self.board[(y * TetrixBoard.BoardWidth) + x] = shape
def timeoutTime(self):
return 1000 / (1 + self.level)
def squareWidth(self):
return self.contentsRect().width() / TetrixBoard.BoardWidth
def squareHeight(self):
return self.contentsRect().height() / TetrixBoard.BoardHeight
def setNextPieceLabel(self, label):
self.nextPieceLabel = label
def sizeHint(self):
return QSize(TetrixBoard.BoardWidth * 15 + self.frameWidth() * 2,
TetrixBoard.BoardHeight * 15 + self.frameWidth() * 2)
def minimumSizeHint(self):
return QSize(TetrixBoard.BoardWidth * 5 + self.frameWidth() * 2,
TetrixBoard.BoardHeight * 5 + self.frameWidth() * 2)
def start(self):
if self.isPaused:
return
self.isStarted = True
self.isWaitingAfterLine = False
self.numLinesRemoved = 0
self.numPiecesDropped = 0
self.score = 0
self.level = 1
self.clearBoard()
self.linesRemovedChanged.emit(self.numLinesRemoved)
self.scoreChanged.emit(self.score)
self.levelChanged.emit(self.level)
self.newPiece()
self.timer.start(self.timeoutTime(), self)
def pause(self):
if not self.isStarted:
return
self.isPaused = not self.isPaused
if self.isPaused:
self.timer.stop()
else:
self.timer.start(self.timeoutTime(), self)
self.update()
def paintEvent(self, event):
super(TetrixBoard, self).paintEvent(event)
painter = QPainter(self)
rect = self.contentsRect()
if self.isPaused:
painter.drawText(rect, Qt.AlignCenter, "Pause")
return
#.........这里部分代码省略.........
示例8: Board
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
#.........这里部分代码省略.........
r'/images/CurtainOnly80x160.gif')
# creating dictionary of brushes!
self.pixmaps = {
1: self.nurse_pixmap,
2: self.nurse_left_pixmap,
3: self.nurse_right_pixmap,
4: self.empty_bed_pixmap,
5: self.girl_alarm_pixmap,
6: self.girl_sleeping_pixmap,
7: self.curtain_pixmap,
8: self.table_top_pixmap,
9: self.table_pixmap
}
@pyqtSlot()
def start(self):
"""
Function responsible for preparing animation when
start button has been pressed
"""
if self.isActive:
return
if self.isStopped:
self.isStopped = False
self.isActive = True
self.timer.start(self.refreshRate, self)
@pyqtSlot()
def stop(self):
"""
Function responsible for stoping animation when
stop button pressed
"""
if not self.isActive:
return
self.isStopped = True
self.isActive = False
self.timer.stop()
self.update()
@pyqtSlot(str)
def move(self, direction):
"""
Function responsible for moving main character up.
"""
self.rotatePlayer(direction)
self.fillRealBoard(self.player_x, self.player_y,
self.player_size, self.player_size, '')
if direction == 'up' and not self.collision(direction):
self.makeStep(direction, -self.move_speed)
elif direction == 'right' and not self.collision(direction):
self.makeStep(direction, self.move_speed)
elif direction == 'down' and not self.collision(direction):
self.makeStep(direction, self.move_speed)
示例9: ScrollArea
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
#.........这里部分代码省略.........
viewport = self.viewport().rect()
dx = pos.x() - viewport.left() - 12
if dx >= 0:
dx = max(0, pos.x() - viewport.right() + 12)
dy = pos.y() - viewport.top() - 12
if dy >= 0:
dy = max(0, pos.y() - viewport.bottom() + 12)
self.steadyScroll(QPoint(dx*10, dy*10))
def scrollTo(self, pos):
"""Scroll the View to get pos (QPoint) in the top left corner (if possible).
Returns the actual distance moved.
"""
return self.scrollBy(pos - self.scrollOffset())
def scrollBy(self, diff):
"""Scroll the View diff pixels (QPoint) in x and y direction.
Returns the actual distance moved.
"""
hbar = self.horizontalScrollBar()
vbar = self.verticalScrollBar()
x = hbar.value()
hbar.setValue(hbar.value() + diff.x())
x = hbar.value() - x
y = vbar.value()
vbar.setValue(vbar.value() + diff.y())
y = vbar.value() - y
return QPoint(x, y)
def kineticScrollTo(self, pos):
"""Scroll the View to get pos (QPoint) in the top left corner (if possible).
Returns the actual distance the scroll area will move.
"""
return self.kineticScrollBy(pos - self.scrollOffset())
def kineticScrollBy(self, diff):
"""Scroll the View diff pixels (QPoint) in x and y direction.
Returns the actual distance the scroll area will move.
"""
ret = self.canScrollBy(diff)
if diff:
scroller = KineticScroller()
scroller.scrollBy(diff)
self.startScrolling(scroller)
return ret
def kineticAddDelta(self, diff):
"""Add diff (QPoint) to an existing kinetic scroll.
If no scroll is active, a new one is started (like kineticScrollBy).
"""
if isinstance(self._scroller, KineticScroller):
self._scroller.scrollBy(self._scroller.remainingDistance() + diff)
else:
self.kineticScrollBy(diff)
def steadyScroll(self, diff):
"""Start steadily scrolling diff (QPoint) pixels per second.
Stops automatically when the end is reached.
"""
if diff:
self.startScrolling(SteadyScroller(diff, self.scrollupdatespersec))
else:
self.stopScrolling()
def startScrolling(self, scroller):
"""Begin a scrolling operation using the specified scroller."""
self._scroller = scroller
if not self._scrollTimer.isActive():
self._scrollTimer.start(1000 / self.scrollupdatespersec, self)
def stopScrolling(self):
"""Stop scrolling."""
if self._scroller:
self._scrollTimer.stop()
self._scroller = None
def isScrolling(self):
"""Return True if a scrolling movement is active."""
return bool(self._scroller)
def timerEvent(self, ev):
"""Called by the _scrollTimer."""
diff = self._scroller.step()
# when scrolling slowly, it might be that no redraw is needed
if diff:
# change the scrollbars, but check how far they really moved.
if not self.scrollBy(diff) or self._scroller.finished():
self.stopScrolling()
示例10: Example
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
#.........这里部分代码省略.........
grnb = QPushButton('Green', self)
grnb.setCheckable(True)
grnb.move(10, 60)
grnb.clicked[bool].connect(self.setColor)
blueb = QPushButton('Blue', self)
blueb.setCheckable(True)
blueb.move(10, 90)
blueb.clicked[bool].connect(self.setColor)
self.square = QFrame(self)
self.square.setGeometry(150, 20, 50, 50)
self.square.setStyleSheet("QWidget { background-color: %s}" %
self.col.name())
# slider 滚动条
sld = QSlider(Qt.Horizontal, self)
sld.setFocusPolicy(Qt.NoFocus)
sld.setGeometry(10, 120, 100, 10)
sld.valueChanged[int].connect(self.changeValue)
self.label = QLabel(self)
self.label.setPixmap(QPixmap('1.png'))
self.label.setGeometry(150, 90, 80, 80)
# 进度条ProgressBar
self.pbar = QProgressBar(self)
self.pbar.setGeometry(10, 170, 200, 20)
self.btn = QPushButton('Start', self)
self.btn.move(10, 200)
self.btn.clicked.connect(self.doAction)
self.timer = QBasicTimer()
self.step = 0
# Calendar 日历
cal = QCalendarWidget(self)
cal.setGridVisible(True)
cal.move(10, 230)
cal.clicked[QDate].connect(self.showDate)
self.lbl = QLabel(self)
date = cal.selectedDate()
self.lbl.setText(date.toString())
self.lbl.move(80, 440)
self.setGeometry(300, 200, 300, 500)
self.setWindowTitle('Toggle')
self.show()
def changeTitle(self, state):
if state == Qt.Checked:
self.setWindowTitle('Toogle')
else:
self.setWindowTitle(' ')
def setColor(self, pressed):
source = self.sender()
if pressed:
val = 255
else:
val = 0
if source.text() == "Red":
self.col.setRed(val)
elif source.text() == "Green":
self.col.setGreen(val)
else:
self.col.setBlue(val)
self.square.setStyleSheet("QFrame {background-color: %s}" % self.col.name())
def changeValue(self, value):
if value == 0:
self.label.setPixmap(QPixmap('1.png'))
elif 0 < value <= 30:
self.label.setPixmap(QPixmap('2.png'))
elif 30 < value < 80:
self.label.setPixmap(QPixmap('3.png'))
else:
self.label.setPixmap(QPixmap('4.png'))
def timerEvent(self, *args, **kwargs):
if self.step >= 100:
self.timer.stop()
self.btn.setText('Finished')
return
self.step += 1
self.pbar.setValue(self.step)
def doAction(self):
if self.timer.isActive():
self.timer.stop()
self.btn.setText('Start')
else:
self.timer.start(100, self)
self.btn.setText('Stop')
def showDate(self, date):
self.lbl.setText(date.toString())
示例11: HAdjustmentBar
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
class HAdjustmentBar(QWidget):
valueChanged = pyqtSignal(int)
def __init__(self, parent=None):
super(HAdjustmentBar, self).__init__(parent)
self.value = 50
self.step = 1
self.hi_value = 100
self.low_value = 50
self.timer_value = 25
self.texttemplate = 'Value = %s'
self.timer = QBasicTimer()
self.showToggleButton = True
self.showSettingMenu = True
self.bar = LabeledBar()
#self.bar.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
# black magic class patching
# so calling these functions actually calls the self.bar's functions.
self.minimum = self.bar.minimum
self.maximum = self.bar.maximum
def buildWidget(self):
layout = QHBoxLayout(self)
layout.setContentsMargins(0,0,0,0)
SettingMenu = QMenu()
exitButton = QAction(QIcon('exit24.png'), 'Set As High', self)
exitButton.triggered.connect(self.setHigh)
SettingMenu.addAction(exitButton)
setlowButton = QAction(QIcon('exit24.png'), 'Set As Low', self)
setlowButton.triggered.connect(self.setLow)
SettingMenu.addAction(setlowButton)
self.tb_down = QToolButton()
self.tb_down.pressed.connect(self.on_click_down)
self.tb_down.released.connect(self.on_released)
self.tb_down.setArrowType(Qt.LeftArrow)
self.tb_up = QToolButton()
self.tb_up.pressed.connect(self.on_click_up)
self.tb_up.released.connect(self.on_released)
self.tb_up.setArrowType(Qt.RightArrow)
if self.showToggleButton:
tb_set = QToolButton()
tb_set.clicked.connect(self.on_click_set_value)
tb_set.setText('<>')
if self.showSettingMenu:
tb_set.setMenu(SettingMenu)
tb_set.setPopupMode(QToolButton.DelayedPopup)
layout.addWidget(self.tb_down)
layout.addWidget(self.bar)
layout.addWidget(self.tb_up)
if self.showToggleButton:
layout.addWidget(tb_set)
layout.setSpacing(0)
def on_click_up(self):
self.timer.start(self.timer_value, self)
self.value += self.step
self._setValue()
def on_click_down(self):
self.timer.start(self.timer_value, self)
self.value -= self.step
self._setValue()
def on_released(self):
self.timer.stop()
def on_click_set_value(self):
if self.value == self.hi_value:
self.value = self.low_value
else:
self.value = self.hi_value
self._setValue()
def timerEvent(self, e):
if self.value < self.maximum() and self.value > self.minimum():
if self.tb_down.isDown():
self.value -= self.step
else:
self.value += self.step
self._setValue()
else:
self.timer.stop()
def _setValue(self):
if self.value < self.minimum():self. value = self.minimum()
if self.value > self.maximum(): self.value = self.maximum()
self.valueChanged.emit(self.value)
def setValue(self, value):
if value < self.minimum(): value = self.minimum()
if value > self.maximum(): value = self.maximum()
self.value = int(value)
tmpl = lambda s: self.texttemplate % s
try:
self.bar.text = tmpl(int(value))
except:
self.bar.text = self.texttemplate
self.bar.setValue(int(value))
#.........这里部分代码省略.........
示例12: YaP
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
class YaP(QWidget):
rate_url = 'poligon.info'
query = ''
query_list = []
res_label = ''
file_path_label = ''
rank = 0
file_taken = False
res_list = []
file_queries = []
fname = ''
r_count = 0
db_path = 'keywords.db'
xls_path = 'rating.xls'
yandex_limits = [
[0, 230, 0], [1, 276, 0], [2, 276, 0],
[3, 276, 0], [4, 276, 0], [5, 230, 0],
[6, 161, 0], [7, 92, 0], [8, 46, 0],
[9, 46, 0], [10, 46, 0], [11, 46, 0],
[12, 46, 0], [13, 46, 0], [14, 46, 0],
[15, 46, 2], [16, 46, 0], [17, 46, 0],
[18, 46, 0], [19, 46, 0], [20, 92, 0],
[21, 161, 0], [22, 230, 0], [23, 240, 0]
]
# req_date = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
req_date = str(datetime.now().strftime('%Y-%m-%d'))
query_url = 'https://yandex.ru/search/xml?user=webmaster-poligon\
&key=03.279908682:25776a70171503eb70359c5bd5b820dc&l10n=ru\
&groupby=groups-on-page%3D100&lr=2&query='
def __init__(self):
super().__init__()
self.initUI()
self.search_btn.clicked.connect(self.set_query)
self.search_btn.clicked.connect(self.start_search)
self.qfile_btn.clicked.connect(self.showOpenDialog)
self.sfile_btn.clicked.connect(self.db_xls)
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
lbl = QLabel('Выбран запрос: ')
grid.addWidget(lbl, 0, 0)
lbl1 = QLabel('Поиск по запросу: ')
grid.addWidget(lbl1, 3, 0)
self.label = QLabel(self)
grid.addWidget(self.label, 0, 1)
self.field = QLineEdit(self)
grid.addWidget(self.field, 3, 1)
self.field.textChanged[str].connect(self.push_query)
self.search_btn = QPushButton('Поиск')
grid.addWidget(self.search_btn, 3, 2)
self.qfile_btn = QPushButton('Файл запросов')
grid.addWidget(self.qfile_btn, 5, 0)
self.sfile_btn = QPushButton('Сохранить')
grid.addWidget(self.sfile_btn, 5, 2)
label_fake = QLabel()
grid.addWidget(label_fake, 4, 0)
label_fake1 = QLabel()
grid.addWidget(label_fake1, 2, 0)
self.label_done = QLabel()
grid.addWidget(self.label_done, 6, 1)
self.label_r = QLabel(self.res_label)
grid.addWidget(self.label_r, 4, 1)
self.label_fp = QLabel(self.file_path_label)
grid.addWidget(self.label_fp, 5, 1)
self.setGeometry(700, 350, 600, 200)
self.setWindowTitle('\"YaP\" - is a Yandex ratings for Poligon.info')
self.pbar = QProgressBar(self)
grid.addWidget(self.pbar, 7, 1)
self.timer = QBasicTimer()
self.step = 0
self.show()
def timerEvent(self, e):
if self.step >= 100:
self.timer.stop()
return
self.step = self.step + 1
self.pbar.setValue(self.step)
def sql_con(self, res_list):
conn = sqlite3.connect(self.db_path)
db = conn.cursor()
db.execute("select name from sqlite_master \
where type='table' and name='requests'")
if db.fetchone():
for res in self.res_list:
if len(self.file_queries) == 0:
k = (self.query.encode('utf-8').decode('cp1251'),
self.req_date,)
db.execute("select * from requests \
where keyword=? and date=?", k)
if db.fetchone():
db.execute("delete from requests \
where keyword=? and date=?", k)
else:
continue
#.........这里部分代码省略.........
示例13: Tetris
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
class Tetris(QMainWindow):
def __init__(self):
super().__init__()
self.isStarted = False
self.isPaused = False
self.nextMove = None
self.lastShape = Shape.shapeNone
self.initUI()
def initUI(self):
self.gridSize = 22
self.speed = 10
self.timer = QBasicTimer()
self.setFocusPolicy(Qt.StrongFocus)
hLayout = QHBoxLayout()
self.tboard = Board(self, self.gridSize)
hLayout.addWidget(self.tboard)
self.sidePanel = SidePanel(self, self.gridSize)
hLayout.addWidget(self.sidePanel)
self.statusbar = self.statusBar()
self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)
self.start()
self.center()
self.setWindowTitle('Tetris')
self.show()
self.setFixedSize(self.tboard.width() + self.sidePanel.width(),
self.sidePanel.height() + self.statusbar.height())
def center(self):
screen = QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2)
def start(self):
if self.isPaused:
return
self.isStarted = True
self.tboard.score = 0
BOARD_DATA.clear()
self.tboard.msg2Statusbar.emit(str(self.tboard.score))
BOARD_DATA.createNewPiece()
self.timer.start(self.speed, self)
def pause(self):
if not self.isStarted:
return
self.isPaused = not self.isPaused
if self.isPaused:
self.timer.stop()
self.tboard.msg2Statusbar.emit("paused")
else:
self.timer.start(self.speed, self)
self.updateWindow()
def updateWindow(self):
self.tboard.updateData()
self.sidePanel.updateData()
self.update()
def timerEvent(self, event):
if event.timerId() == self.timer.timerId():
if TETRIS_AI and not self.nextMove:
self.nextMove = TETRIS_AI.nextMove()
if self.nextMove:
k = 0
while BOARD_DATA.currentDirection != self.nextMove[0] and k < 4:
BOARD_DATA.rotateRight()
k += 1
k = 0
while BOARD_DATA.currentX != self.nextMove[1] and k < 5:
if BOARD_DATA.currentX > self.nextMove[1]:
BOARD_DATA.moveLeft()
elif BOARD_DATA.currentX < self.nextMove[1]:
BOARD_DATA.moveRight()
k += 1
# lines = BOARD_DATA.dropDown()
lines = BOARD_DATA.moveDown()
self.tboard.score += lines
if self.lastShape != BOARD_DATA.currentShape:
self.nextMove = None
self.lastShape = BOARD_DATA.currentShape
self.updateWindow()
else:
super(Tetris, self).timerEvent(event)
def keyPressEvent(self, event):
#.........这里部分代码省略.........
示例14: FieldUI
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
class FieldUI(QFrame):
def __init__(self, parent, game):
super().__init__(parent)
self.main_window = parent
self.game = game
self.rocks = self.game.rocks
self.powerups = self.game.powerups
self.bullets = self.game.bullets
self.width, self.height = self.game.dimensions
self.init_timers()
self.start_timers()
self.player_ui = PlayerUI(self, self.game)
self.init_signals()
self.setFocusPolicy(Qt.StrongFocus)
def init_timers(self):
"""Initializes the timers in the game."""
self.game_timer = QBasicTimer()
self.rock_timer = QBasicTimer()
self.level_timer = QBasicTimer()
self.powerup_timer = QBasicTimer()
self.ticker_timer = QBasicTimer()
self.bullet_timer = QBasicTimer()
self.player_invincibility_timer = QBasicTimer()
self.big_bomb_timer = QBasicTimer()
self.slow_down_rocks_timer = QBasicTimer()
self.shoot_rocks_timer = QBasicTimer()
self.powerup_duration_timer = QTimer()
def start_timers(self):
"""Starts the timers in the game."""
self.game_timer.start(self.game.game_speed, self)
self.rock_timer.start(self.game.rock_speed, self)
self.level_timer.start(self.game.level_speed, self)
self.powerup_timer.start(self.game.rock_speed, self)
self.player_invincibility_timer.start(int(PowerupTimeInterval.medium),
self)
self.big_bomb_timer.start(int(PowerupTimeInterval.big), self)
self.slow_down_rocks_timer.start(int(PowerupTimeInterval.medium), self)
self.shoot_rocks_timer.start(int(PowerupTimeInterval.very_big), self)
self.bullet_timer.start(self.game.bullet_speed, self)
def stop_timers(self):
"""Stops the timers in the game."""
self.game_timer.stop()
self.rock_timer.stop()
self.level_timer.stop()
self.powerup_timer.stop()
self.ticker_timer.stop()
self.bullet_timer.stop()
self.player_invincibility_timer.stop()
self.big_bomb_timer.stop()
self.slow_down_rocks_timer.stop()
self.shoot_rocks_timer.stop()
self.powerup_duration_timer.stop()
def init_signals(self):
"""Initializes the signals in the game that connect to a method and
calls it after the singnals are emitted.
"""
self.com = Communicate()
self.com.move_left.connect(self.player_ui.move_left)
self.com.move_right.connect(self.player_ui.move_right)
self.com.restart.connect(self.main_window.restart_game)
self.com.exit.connect(UserInterface.close_app)
self.com.win.connect(self.win_the_game)
def timerEvent(self, event):
"""Gets the emitted events from the timers and calls the appropriate
methods for each of them.
"""
self.powerups_timer_events(event)
self.gameplay_timer_events(event)
if event.timerId() == self.ticker_timer.timerId():
self.ticker["value"] -= 1
if self.ticker["type"] == "player_invincibility":
self.show_player_invincibility_info(self.ticker["value"])
if self.ticker["type"] == "slow_down_rocks":
self.show_slow_down_rocks_info(self.ticker["value"])
if self.ticker["type"] == "shoot_rocks":
self.show_shoot_rocks_info(self.ticker["value"])
self.bullet_ui = BulletUI(self, self.game, self.player_ui)
self.bullets.append(self.bullet_ui)
else:
super(FieldUI, self).timerEvent(event)
def gameplay_timer_events(self, event):
"""Gets the emitted events from the timers related to the gameplay and
calls the appropriate methods and initializes the appropriate objects
for each of them.
"""
if event.timerId() == self.game_timer.timerId():
self.rock_ui = RockUI(self, self.game)
#.........这里部分代码省略.........
示例15: CheckCreds
# 需要导入模块: from PyQt5.QtCore import QBasicTimer [as 别名]
# 或者: from PyQt5.QtCore.QBasicTimer import stop [as 别名]
class CheckCreds(QDialog):
"""
This class manages the authentication process for oVirt. If credentials are saved, they're
tried automatically. If they are wrong, the username/password dialog is shown.
"""
def __init__(self, parent, username, password, remember):
QDialog.__init__(self, parent)
self.uname = username
self.pw = password
self.remember = False if conf.CONFIG['allow_remember'] == '0' else remember
self.setModal(True)
self.initUI()
def initUI(self):
"""
Description: A progress bar, a status message will be shown and a timer() method will
be invoked as part of the authentication process.
Arguments: None
Returns: Nothing
"""
self.pbar = QProgressBar(self)
self.pbar.setGeometry(30, 40, 200, 25)
self.status = QLabel(self)
self.status.setGeometry(30, 75, 200, 20)
self.timer = QBasicTimer()
self.step = 0
self.setGeometry(300, 300, 255, 100)
self.center()
self.setWindowTitle(_('loading'))
self.show()
self.timer.start(100, self)
def timerEvent(self, e):
"""
Description: Called periodically as part of the QBasicTimer() object.
Authentication will be handled within this method.
Arguments: The event. Won't be used, though.
Returns: Nothing, just exits when progress bar reaches 100%
"""
global conf
err = QMessageBox()
self.status.setText(_('authenticating'))
if not conf.USERNAME:
try:
kvm = API(url=conf.CONFIG['ovirturl'], username=self.uname + '@' + conf.CONFIG['ovirtdomain'], password=self.pw, insecure=True, timeout=int(conf.CONFIG['conntimeout']), filter=True)
conf.OVIRTCONN = kvm
conf.USERNAME = self.uname
conf.PASSWORD = self.pw
self.status.setText(_('authenticated_and_storing'))
self.step = 49
except ConnectionError as e:
err.critical(self, _('apptitle') + ': ' + _('error'), _('ovirt_connection_error') + ': ' + sub('<[^<]+?>', '', str(e)))
self.status.setText(_('error_while_authenticating'))
self.step = 100
except RequestError as e:
err.critical(self, _('apptitle') + ': ' + _('error'), _('ovirt_request_error') + ': ' + sub('<[^<]+?>', '', str(e)))
self.status.setText(_('error_while_authenticating'))
self.step = 100
if self.step >= 100:
# Authenticacion process has concluded
self.timer.stop()
self.close()
return
elif self.step == 50:
# Credentials were ok, we check whether we should store them for further uses
if self.remember:
self.status.setText(_('storing_credentials'))
with os.fdopen(os.open(conf.USERCREDSFILE, os.O_WRONLY | os.O_CREAT, 0600), 'w') as handle:
handle.write('[credentials]\nusername=%s\npassword=%s' % (self.uname, encode(self.pw, 'rot_13')))
handle.close()
self.step = 99
else:
self.status.setText(_('successfully_authenticated'))
self.step = 99
self.step = self.step + 1
self.pbar.setValue(self.step)