本文整理汇总了Python中PyQt5.QtWidgets.QProgressBar.setRange方法的典型用法代码示例。如果您正苦于以下问题:Python QProgressBar.setRange方法的具体用法?Python QProgressBar.setRange怎么用?Python QProgressBar.setRange使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QProgressBar
的用法示例。
在下文中一共展示了QProgressBar.setRange方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: extract2csv
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
def extract2csv(self, tabWidget, d):
name = tabWidget.tabText(tabWidget.currentIndex())
wid = tabWidget.currentWidget()
start = wid.dateStart.text()
end = wid.dateEnd.text()
end = False if end == 'Now' else end
fail = []
progress = QProgressBar()
progress.setRange(0, len(self.tabCsv))
d.layout().addWidget(progress)
progress.setValue(0)
for i, device in enumerate(self.tabCsv[name]):
try:
dataFrame = self.db.dataBetween(device.tablename, ','.join(device.keys), start=start, end=end)
dataFrame.to_csv('/tmp/PFS-%s-%s.csv' % (start[:-6], device.tablename))
progress.setValue(i + 1)
except Exception as e:
print (e)
fail.append(device.tablename)
if fail:
self.showInformation("Extraction error on %s" % ','.join(fail))
else:
self.showInformation("Extraction Completed")
d.close()
示例2: BusyProgressDialog
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
class BusyProgressDialog(QDialog):
"""
This class implements a dialog showing a busy progress bar.
"""
def __init__(self, title='', parent=None):
"""
Initialize the form dialog.
:type title: str
:type parent: QWidget
"""
super().__init__(parent)
self.progressBar = QProgressBar(self)
self.progressBar.setAlignment(Qt.AlignHCenter)
self.progressBar.setRange(0, 0)
self.progressBar.setFixedSize(300, 30)
self.progressBar.setTextVisible(True)
self.progressBar.setFormat(title or 'Busy ...')
self.mainLayout = QVBoxLayout(self)
self.mainLayout.addWidget(self.progressBar)
self.setWindowIcon(QIcon(':/images/eddy'))
self.setWindowTitle(title or 'Busy ...')
self.setFixedSize(self.sizeHint())
####################################################################################################################
# #
# CONTEXT MANAGER #
# #
####################################################################################################################
def __enter__(self):
"""
Draw the dialog.
"""
self.show()
def __exit__(self, exc_type, exc_value, traceback):
"""
Close the dialog.
"""
self.close()
示例3: SplashScreen
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
class SplashScreen(QWidget):
"""
A splash screen window with an image, a textbox for current status, and a progress bar.
"""
def __init__(self):
super().__init__()
self.setWindowFlags(Qt.FramelessWindowHint)
self.setWindowTitle(_('Recharify loading...'))
QLabel(_('Loading splash screen image...'), self).move(15, 10)
self.progress = QProgressBar(self)
self.progress.setRange(0, 100)
self.progress.setGeometry(0, 0, 250, 20)
self.setGeometry(300, 300, 250, 150)
self.movetocenter()
def movetocenter(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def progress_change(self, p):
self.progress.setValue(p)
示例4: QApplication
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# See http://doc.qt.io/qt-5/qprogressbar.html#details
import sys
from PyQt5.QtWidgets import QApplication, QProgressBar, QWidget, QVBoxLayout
app = QApplication(sys.argv)
window = QWidget()
progressbar_1 = QProgressBar()
progressbar_1.setRange(0, 100)
progressbar_1.setValue(70)
progressbar_2 = QProgressBar()
progressbar_2.setRange(0, 0)
vbox = QVBoxLayout()
vbox.addWidget(progressbar_1)
vbox.addWidget(progressbar_2)
window.setLayout(vbox)
window.show()
# The mainloop of the application. The event handling starts from this point.
# The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead.
示例5: QApplication
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
import sys
import asyncio
import time
from PyQt5.QtWidgets import QApplication, QProgressBar
from quamash import QThreadExecutor, QEventLoop
app = QApplication(sys.argv)
loop = QEventLoop(app)
asyncio.set_event_loop(loop)
progress = QProgressBar()
progress.setRange(0, 99)
progress.show()
@asyncio.coroutine
def master():
yield from first_50()
with QThreadExecutor(1) as exec:
yield from loop.run_in_executor(exec, last_50)
@asyncio.coroutine
def first_50():
for i in range(50):
progress.setValue(i)
yield from asyncio.sleep(.1)
def last_50():
for i in range(50, 100):
loop.call_soon_threadsafe(progress.setValue, i)
示例6: RF_Qt
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
#.........这里部分代码省略.........
self.darken_amount_opt.setEnabled(False)
self.darken_amount_opt.setToolTip(
"<qt/>Set the amount to darken a font by. 50 is considered turning a "
"regular weight font into a bold weight font. It is not recommended to "
"darken a font that much however."
)
self.darken_amount_opt.valueChanged[int].connect(self.set_darken_amount)
hb_dark_opt.addWidget(self.darken_amount_opt)
self.darken_amount_lab = QLabel()
self.darken_amount_lab.setText(str(self.darken_amount_opt.value()))
self.darken_amount_lab.setEnabled(False)
hb_dark_opt.addWidget(self.darken_amount_lab)
gb_dark_opt.setLayout(hb_dark_opt)
win_layout.addWidget(gb_dark_opt)
# Buttons #
hb_buttons = QHBoxLayout()
# hb_buttons.addStretch()
self.gen_ttf_btn = QPushButton("Generate TTF")
self.gen_ttf_btn.setEnabled(False)
self.gen_ttf_btn.setToolTip(
"<qt/>Generate a new TrueType font based on the options chosen in this program. "
"<br /><br />"
"The new fonts are saved in a directory of your choosing."
)
self.gen_ttf_btn.clicked.connect(self.gen_ttf)
hb_buttons.addWidget(self.gen_ttf_btn)
self.load_font_btn = QPushButton("Load Fonts")
self.load_font_btn.setToolTip("<qt/>Load font files to modify.")
self.load_font_btn.clicked.connect(self.load_fonts)
hb_buttons.addWidget(self.load_font_btn)
self.prog_bar = QProgressBar()
self.prog_bar.setRange(0, 100)
hb_buttons.addWidget(self.prog_bar)
win_layout.addLayout(hb_buttons)
# Output Log #
gb_log_win = QGroupBox("Log Window")
gb_log_win.setStyleSheet(gb_style)
vb_log = QVBoxLayout()
out_font = QFont("Courier")
out_font.setStyleHint(QFont.Monospace)
self.log_win = QTextEdit()
self.log_win.setAcceptRichText(False)
self.log_win.setFont(out_font)
vb_log.addWidget(self.log_win)
gb_log_win.setLayout(vb_log)
win_layout.addWidget(gb_log_win)
# Show Window #
self.setCentralWidget(QWidget(self))
self.centralWidget().setLayout(win_layout)
self.setWindowTitle("Readify Font")
self.show()
# Check if fontforge is actually in users PATH. If it isn't, prompt user to provice a location
self.ff_path = helper.which("fontforge")
if not self.ff_path:
self.set_ff_path()
def set_ff_path(self):
"""
Let user choose location of fontforge
:return:
示例7: XNCStatusBar
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
class XNCStatusBar(QStatusBar):
def __init__(self, parent=None):
super(XNCStatusBar, self).__init__(parent)
# state vars
self.world = XNovaWorld_instance()
# initialization
self.setSizeGripEnabled(True)
# sub-widgets
# progressbar
self._progressbar = QProgressBar(self)
self._progressbar.hide()
self._progressbar.setValue(0)
self._progressbar.setRange(0, 99)
# online players counter
self._lbl_online = QLabel(self.tr('Online') + ': 0', self)
# label with loading.gif
self._loading_gif = QMovie(':/i/loading.gif')
self._lbl_loading = QLabel(self)
self._lbl_loading.setMovie(self._loading_gif)
self._lbl_loading.hide()
# testing only
self._btn_runscript = QPushButton('Run script', self)
self._btn_runscript.clicked.connect(self.on_run_script)
self.addPermanentWidget(self._btn_runscript)
#
self.addPermanentWidget(self._lbl_loading)
self.addPermanentWidget(self._lbl_online) # should be las right widget
self.show()
def set_status(self, msg: str, timeout: int=0):
self.showMessage(msg, timeout)
def set_loading_status(self, loading: bool):
if loading:
self._lbl_loading.show()
self._loading_gif.start()
else:
self._loading_gif.stop()
self._lbl_loading.hide()
def set_world_load_progress(self, comment: str, progress: int):
"""
Display world load progress in status bar
:param comment: string comment of what is currently loading
:param progress: percent progress, or -1 to disable
"""
if progress != -1:
if not self._progressbar.isVisible():
self.insertPermanentWidget(0, self._progressbar)
self._progressbar.show()
msg = self.tr('Loading world') + ' ({0}%) {1}...'.format(progress, comment)
logger.debug(msg)
self._progressbar.setValue(progress)
self.set_status(msg)
else:
self.removeWidget(self._progressbar)
self._progressbar.hide()
self._progressbar.reset()
self.clearMessage()
def update_online_players_count(self):
op = self.world.get_online_players()
self._lbl_online.setText(self.tr('Online') + ': {0}'.format(op))
# some functions may be useful, documentation:
# void QStatusBar::clearMessage()
# void QStatusBar::addPermanentWidget(QWidget * widget, int stretch = 0)
# void QStatusBar::addWidget(QWidget * widget, int stretch = 0)
# void QStatusBar::removeWidget(QWidget * widget)
@pyqtSlot()
def on_run_script(self):
files = os.listdir('scripts')
files.sort()
script_files = [fn for fn in files if fn[0] != '.' and fn.endswith('.py')]
# print(script_files)
menu = QMenu(self)
for script_filename in script_files:
act = QAction(menu)
act.setText('Run "scripts/' + script_filename + '"...')
act.setData('scripts/' + script_filename)
menu.addAction(act)
act_ret = menu.exec(QCursor.pos())
if act_ret is None:
return
script_filename = str(act_ret.data())
s = ''
try:
with open(script_filename, 'rt', encoding='utf-8') as f:
s = f.read()
except IOError:
pass
if s != '':
exec(s)
示例8: ProgressDialog
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
class ProgressDialog(QDialog):
signal = pyqtSignal()
#################################################
# コンストラクタ
#################################################
def __init__(self, imagePath, ckptPath, resultPath, parent=None):
super(ProgressDialog, self).__init__(parent)
self.imagePath = imagePath
self.ckptPath = ckptPath
self.resultPath = resultPath
self.init_widgets()
#################################################
# Widgetsの初期化
#################################################
def init_widgets(self):
layout = QVBoxLayout()
# Message Label
msgLabel = QLabel('画像を識別しています。しばらくお待ちください。')
msgLabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
layout.addWidget(msgLabel)
# Progress Bar
self.prgsBar = QProgressBar()
self.prgsBar.setRange(0, MAX_RANGE)
self.prgsBar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
layout.addWidget(self.prgsBar)
self.setWindowTitle('画像識別')
self.setLayout(layout)
#################################################
# 表示
#################################################
def show(self):
# Timer 200ミリ秒周期で5%進捗を進める
self.timer = QTimer(self)
self.timer.setInterval(200)
self.timer.timeout.connect(self.timerEvent)
self.timer.start()
# 初期値は0%
self.step = 0
self.prgsBar.setValue(self.step)
# 識別開始
self.thread = IdentifyThread(self.imagePath, self.ckptPath, self.resultPath)
self.thread.finished.connect(self.identify_finished)
self.thread.start()
# ダイアログ表示
super(ProgressDialog, self).show()
#################################################
# 識別終了イベント
#################################################
def identify_finished(self):
if (self.thread is not None):
self.thread.wait()
self.thread = None
self.signal.emit()
self.close()
#################################################
# タイマーイベント
#################################################
def timerEvent(self):
self.step += 1
self.prgsBar.setValue(self.step)
#################################################
# 終了
#################################################
def close(self):
super(ProgressDialog, self).close()
示例9: SettingsGUI
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
class SettingsGUI(QWidget):
def __init__(self, parent = None):
super(SettingsGUI, self).__init__(parent)
self.setAcceptDrops(True)
finish_layout = QVBoxLayout()
self.btn_finish_perf = QCheckBox(self.tr('Add the film perforations'))
finish_layout.addWidget(self.btn_finish_perf)
self.btn_finish_helix = QCheckBox(self.tr('Make a helical image'))
finish_layout.addWidget(self.btn_finish_helix)
self.btn_finish_rect = QCheckBox(self.tr('Make a rectangular image'))
finish_layout.addWidget(self.btn_finish_rect)
self.pbar = QProgressBar()
self.pbar.setValue(0)
self.pbar.setRange(0,8)
finish_layout.addWidget(self.pbar)
self.setLayout(finish_layout)
self.setWindowTitle("Drag&Drop files")
def start_process(self):
logger = logging.getLogger()
self.pbar.setValue(0)
if self.filename[-6:] == ".pngs/":
self.filename = self.filename[:-1]
cachedimage = CachedImage("inherit",
dir=self.filename,
disposal=False)
logger.debug(":: {0}".format(cachedimage))
img = cachedimage.get_region(None)
else:
img = cv2.imread(self.filename)
file_name = self.filename
self.pbar.setValue(1)
if self.btn_finish_perf.isChecked():
img = film.filmify( img )
self.pbar.setValue(2)
file_name += ".film.png"
cv2.imwrite(file_name, img)
self.pbar.setValue(3)
if self.btn_finish_helix.isChecked():
self.pbar.setValue(4)
himg = helix.helicify( img )
self.pbar.setValue(5)
cv2.imwrite(file_name + ".helix.png", himg)
if self.btn_finish_rect.isChecked():
self.pbar.setValue(6)
rimg = rect.rectify( img )
self.pbar.setValue(7)
cv2.imwrite(file_name + ".rect.png", rimg)
self.pbar.setValue(8)
def dragEnterEvent(self, event):
logger = logging.getLogger()
event.accept()
mimeData = event.mimeData()
logger.debug('dragEnterEvent')
for mimetype in mimeData.formats():
logger.debug('MIMEType: {0}'.format(mimetype))
logger.debug('Data: {0}'.format(mimeData.data(mimetype)))
def dropEvent(self, event):
logger = logging.getLogger()
event.accept()
mimeData = event.mimeData()
logger.debug('dropEvent')
for mimetype in mimeData.formats():
logger.debug('MIMEType: {0}'.format(mimetype))
logger.debug('Data: {0}'.format(mimeData.data(mimetype)))
#Open only when:
#1. Only file is given
#3. and the mimetipe is text/uri-list
#2. That has the regular extension.
logger.debug("len:{0}".format(len(mimeData.formats())))
if len(mimeData.formats()) == 1:
mimetype = mimeData.formats()[0]
if mimetype == "text/uri-list":
data = mimeData.data(mimetype)
from urllib.parse import urlparse, unquote
for line in bytes(data).decode('utf8').splitlines():
parsed = urlparse(unquote(line))
logger.debug('Data: {0}'.format(parsed))
if parsed.scheme == 'file':
self.filename = parsed.path
#Start immediately
self.start_process()
示例10: Objetives
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
class Objetives(QWidget):
NumButtons = 3
def __init__(self, parent=None):
super(Objetives, self).__init__(parent)
self.createDisplay()
self.createDisplayAverage()
self.createButtons()
self.numVictory = 0
self.numLosses = 0
mainLayout = QGridLayout()
mainLayout.addWidget(self.displayLCD)
mainLayout.addWidget(self.horizontalGroupBox)
mainLayout.addWidget(self.displayWinPercent)
self.setLayout(mainLayout)
self.setWindowTitle("Objetives")
def createButtons(self):
self.horizontalGroupBox = QGroupBox("")
layout = QGridLayout()
self.victoryButton = self.createButton("Victory", "+",self.addVictoryOrLosses)
self.lossesButton = self.createButton("Losses", "+",self.addVictoryOrLosses)
self.victoryDecreaseButton = self.createButton("DV","-",self.addVictoryOrLosses)
self.losseDecreaseButton = self.createButton("DL","-",self.addVictoryOrLosses)
self.lossesButton.setMinimumWidth(150)
self.victoryButton.setMinimumWidth(150)
self.losseDecreaseButton.setMaximumHeight(20)
self.victoryDecreaseButton.setMaximumHeight(20)
layout.addWidget(self.victoryButton, 0, 0, 1, 1)
layout.addWidget(self.lossesButton, 0, 2, 1, 1)
layout.addWidget(self.victoryDecreaseButton, 1, 0, 1, 1)
layout.addWidget(self.losseDecreaseButton, 1, 2, 1, 1)
self.horizontalGroupBox.setLayout(layout)
def createDisplayAverage(self):
self.displayWinPercent = QGroupBox("Wins")
layout = QHBoxLayout()
self.progressBar = QProgressBar()
self.progressBar.setRange(0, 100)
# self.progressBar.setValue(5000)
layout.addWidget(self.progressBar)
self.displayWinPercent.setLayout(layout)
def createDisplay(self):
self.displayLCD = QGroupBox("")
layout = QHBoxLayout()
paletteLosses = QPalette()
paletteVictory = QPalette()
paletteLosses.setColor(paletteLosses.WindowText, QColor(255, 000, 000))
paletteVictory.setColor(paletteVictory.WindowText, QColor(000, 255, 000))
self.lossesLcd = QLCDNumber(3)
self.lossesLcd.setSegmentStyle(QLCDNumber.Filled)
self.lossesLcd.setPalette(paletteLosses)
self.victoryLcd = QLCDNumber(3)
self.victoryLcd.setSegmentStyle(QLCDNumber.Filled)
self.victoryLcd.setPalette(paletteVictory)
self.lossesLcd.setMinimumHeight(100)
self.victoryLcd.setMinimumHeight(100)
self.lossesLcd.setMinimumWidth(150)
self.victoryLcd.setMinimumWidth(150)
layout.addWidget(self.victoryLcd)
layout.addWidget(self.lossesLcd)
self.displayLCD.setLayout(layout)
def addVictoryOrLosses(self):
clickedButton = self.sender()
clickedOperator = clickedButton.text()
operand = float(1)
if clickedOperator == "Victory":
self.numVictory = self.numVictory + 1
self.victoryLcd.display(str(self.numVictory))
if clickedOperator == "DV":
self.numVictory = self.numVictory - 1
self.victoryLcd.display(str(self.numVictory))
if clickedOperator == "Losses":
self.numLosses = self.numLosses + 1
#.........这里部分代码省略.........
示例11: BuildProgressWidget
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
class BuildProgressWidget(QFrame):
BPW_TYPE_SHIPYARD = 'shipyard'
BPW_TYPE_RESEARCH = 'research'
requestCancelBuild = pyqtSignal(XNPlanetBuildingItem)
requestCancelBuildWithPlanet = pyqtSignal(XNPlanetBuildingItem, int)
def __init__(self, parent=None):
super(BuildProgressWidget, self).__init__(parent)
self._planet = XNPlanet()
self._bitem = XNPlanetBuildingItem()
# create UI
self._layout = QHBoxLayout()
self._layout.setContentsMargins(1, 1, 1, 1)
self._layout.setSpacing(1)
self.setLayout(self._layout)
# label - planet name (0)
self._lbl_planetName = QLabel(self)
self._lbl_planetName.setText('')
font = self._lbl_planetName.font()
font.setWeight(QFont.Bold) # fix label font weight to bold
self._lbl_planetName.setFont(font)
self._lbl_planetName.setMinimumWidth(120)
self._layout.addWidget(self._lbl_planetName)
# label - planet coords (1)
self._lbl_planetCoords = QLabel(self)
self._lbl_planetCoords.setText(' [0:0:0] ')
self._lbl_planetCoords.setMinimumWidth(70)
self._layout.addWidget(self._lbl_planetCoords)
# label - building name (and lvl) (2)
self._lbl_buildName = QLabel(self)
self._lbl_buildName.setText('')
self._lbl_buildName.setMinimumWidth(220)
self._layout.addWidget(self._lbl_buildName)
# label - build time left (3)
self._lbl_buildTime = QLabel(self)
self._lbl_buildTime.setText('')
self._lbl_buildTime.setMinimumWidth(70)
self._layout.addWidget(self._lbl_buildTime)
# progress bar (4)
self._pb = QProgressBar(self)
self._pb.setRange(0, 99)
self._pb.setValue(0)
self._layout.addWidget(self._pb)
# button cancel (5)
self._btn_cancel = QPushButton(self)
self._btn_cancel.setText('')
self._btn_cancel.setIcon(QIcon(':i/cancel.png'))
self._layout.addWidget(self._btn_cancel)
self._btn_cancel.clicked.connect(self.on_btn_cancel)
def __str__(self) -> str:
ret = ''
if self._planet is not None:
ret += self._planet.name + ' '
if self._bitem is not None:
ret += self._bitem.name
if self._bitem.is_shipyard_item:
ret += ' (shipyard)'
if self._bitem.is_research_item or \
self._bitem.is_researchfleet_item:
ret += ' (research)'
return ret
def hide(self):
super(BuildProgressWidget, self).hide()
self._planet = None
self._bitem = None
def hide_planet_name(self):
self._lbl_planetName.hide()
self._lbl_planetCoords.hide()
def _set_percent_complete(self, bi: XNPlanetBuildingItem):
secs_passed = bi.seconds_total - bi.seconds_left
percent_complete = (100 * secs_passed) // bi.seconds_total
self._pb.setValue(percent_complete)
def _set_buildtime(self, bi: XNPlanetBuildingItem):
# calc and set time left
secs_left = bi.seconds_left
hours_left = secs_left // 3600
secs_left -= hours_left * 3600
mins_left = secs_left // 60
secs_left -= mins_left * 60
bl_str = '({0:02}:{1:02}:{2:02})'.format(
hours_left, mins_left, secs_left)
self._lbl_buildTime.setText(bl_str)
def update_from_planet(self, planet: XNPlanet, typ: str = ''):
self._planet = planet
self._bitem = None
# config UI
self._lbl_planetName.setText(planet.name)
self._lbl_planetCoords.setText(' [{0}:{1}:{2}] '.format(
planet.coords.galaxy,
planet.coords.system,
planet.coords.position))
if typ == '':
#.........这里部分代码省略.........
示例12: ProgressBar
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
class ProgressBar(vip_base):
def cb_initialize_plugin(self):
# ---------------------------
# Read configuration
# ---------------------------
# Note: this cfg items have to exist!
self.config = self.pl_get_current_config_ref()
self.progress_value = self.config['progress_value']['value']
self.trigger_value = self.config['trigger_value']['value']
self.reset_trigger_value = self.config['reset_trigger_value']['value']
self.show_percent = self.config['show_percent']['value'] == '1'
self.show_current_max = self.config['show_current_max']['value'] == '1'
self.round_digit = int(self.config['round_digit']['value'])
self.min_range = float(self.config['min_rage']['value'])
self.max_range = float(self.config['max_range']['value'])
# --------------------------------
# Create Widget
# --------------------------------
# Create Widget needed for this plugin
self.progressbar = QProgressBar()
self.progressbar.setRange(0, 100)
self.progressbar.setTextVisible(True)
self.progressbar.setValue(0)
self.progressbar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.progressbar.customContextMenuRequested.connect(self.show_context_menu)
# This call is important, because the background structure needs to know the used widget!
# In the background the qmidiwindow will becreated and the widget will be added
self.set_value(self.min_range)
self.pl_set_widget_for_internal_usage(self.progressbar)
# ---------------------------
# Create Parameters
# ---------------------------
para_list = []
# create a parameter object
self.para_trigger = DParameter('trigger', default=0)
self.para_change_progress_value = DParameter('ProgressValue', default=self.progress_value)
self.para_change_reset_value = DParameter('ResetValue', default=self.reset_trigger_value)
self.para_change_trigger_value = DParameter('TriggerValue', default=self.trigger_value)
self.para_change_min_range = DParameter('MinRange', default=self.min_range, Regex=pc.REGEX_SIGNED_FLOAT_OR_INT)
self.para_change_max_range = DParameter('MaxRange', default=self.max_range, Regex=pc.REGEX_SIGNED_FLOAT_OR_INT)
self.para_show_percent = DParameter('ShowPercent', default=self.config['show_percent']['value'], Regex=pc.REGEX_BOOL_BIN)
self.para_show_current_max = DParameter('ShowCurrentMax', default=self.config['show_current_max']['value'], Regex=pc.REGEX_BOOL_BIN)
para_list.append(self.para_trigger)
para_list.append(self.para_change_progress_value)
para_list.append(self.para_change_reset_value)
para_list.append(self.para_change_trigger_value)
para_list.append(self.para_change_min_range)
para_list.append(self.para_change_max_range)
para_list.append(self.para_show_percent)
para_list.append(self.para_show_current_max)
# build parameter list to send to Core
self.pl_send_new_parameter_list(para_list)
return True
def show_context_menu(self, pos):
gloPos = self.progressbar.mapToGlobal(pos)
self.cmenu = self.pl_create_control_context_menu()
self.cmenu.exec_(gloPos)
def cb_pause(self):
# will be called, when plugin gets paused
# can be used to get plugin in a defined state before pause
# e.a. close communication ports, files etc.
pass
def cb_resume(self):
# will be called when plugin gets resumed
# can be used to wake up the plugin from defined pause state
# e.a. reopen communication ports, files etc.
pass
def cb_execute(self, Data=None, block_name = None, plugin_uname = None):
# Do main work here!
# If this plugin is an IOP plugin, then there will be no Data parameter because it wont get data
# If this plugin is a DPP, then it will get Data with data
# param: Data is a Data hash and block_name is the block_name of Data origin
# Data is a hash, so use ist like: Data[CORE_TIME_SIGNAL] = [t1, t2, ...] where CORE_TIME_SIGNAL is a signal_name
# hash signal_name: value
# Data could have multiple types stored in it e.a. Data['d1'] = int, Data['d2'] = []
if self.reset_trigger_value in Data:
self.reset()
#.........这里部分代码省略.........
示例13: DownloadConfigurationPanel
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
class DownloadConfigurationPanel(QDialog):
"""docstring for DownloadConfigurationPanel"""
def __init__(self):
super(DownloadConfigurationPanel, self).__init__()
self.portnum = ''
self.config = ''
self.initLayout()
self.initSettingsLayout()
def initSettingsLayout(self):
# imposto la grandezza del font
self.setStyleSheet('font-size: 11pt;')
self.setWindowIcon(QIcon("icons/download-configuration.png"))
# imposto il titolo della finestra
self.setWindowTitle("Download configuration from beaglebone")
# imposto le dimensioni della finestra
self.setGeometry(0, 0, 350, 200)
# sposta la finestra al centro del desktop
self.centerOnScreen()
def initLayout(self):
boldfont = QFont()
boldfont.setBold(True)
serial_layout = QHBoxLayout()
serial_lbl = QLabel('COM Port:')
serial_lbl.setFont(boldfont)
serial_layout.addWidget(serial_lbl)
serials_c = QComboBox(self)
self.serials_list = list(serial.tools.list_ports.comports())
# imposto la porta selezionata con il primo elemento della lista
self.portnum = self.serials_list[0][0]
for ser in self.serials_list:
serials_c.addItem(ser[1])
serials_c.activated.connect(self.selectSerial)
serial_layout.addWidget(serials_c)
serial_layout.addStretch(1)
bottom_layout = QHBoxLayout()
close_btn = QPushButton('Close')
close_btn.clicked.connect(self.close)
bottom_layout.addStretch(1)
bottom_layout.addWidget(close_btn)
self.progressBar = QProgressBar(self)
self.progressBar.setRange(0,100)
main_layout = QVBoxLayout()
main_layout.addLayout(serial_layout)
main_layout.addStretch(1)
download_btn = QPushButton('Start download')
download_btn.clicked.connect(self.downloadFile)
main_layout.addWidget(download_btn)
#main_layout.addWidget(horizontalLine)
main_layout.addStretch(1)
main_layout.addWidget(self.progressBar)
main_layout.addStretch(1)
main_layout.addLayout(bottom_layout)
self.setLayout(main_layout)
def downloadFile(self):
#print ("Sono dentro downloadFile")
if self.portnum:
try:
#print ("Sono dentro downloadFile e mi sto per collegare")
ser = serial.Serial(self.portnum, timeout=3)
### TEST
#ser = serial.Serial("/dev/pts/26", timeout=3)
ser.write("SENDCFG".encode())
self.progressBar.setValue(25)
time.sleep(1)
data = ser.read().decode()
waiting = ser.inWaiting()
if waiting > 0:
data += ser.read(waiting).decode()
self.progressBar.setValue(50)
print (data)
edata = data.split("\n")
done = False
for line in edata:
if line[:8] == "CFGJSON:":
print ("Carico: "+line[8:])
self.config = json.loads(line[8:])
self.progressBar.setValue(100)
self.informationMessage('Downloaded', 'File downloaded successfully')
done = True
if done == False:
self.progressBar.setValue(0)
self.warningMessage('Error', 'No configuration received...')
else:
self.warningMessage('Error', 'Errore nella lettura dalla seriale')
ser.close()
except Exception as e:
self.criticalMessage('Errore', str(e) + str(traceback.format_exc()))
else:
self.warningMessage('Error', 'Selezionare una porta')
def getConfig(self):
#.........这里部分代码省略.........
示例14: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
class MainWindow(QMainWindow, Ui_MainWindow):
# Maintain the list of browser windows so that they do not get garbage
# collected.
_window_list = []
def __init__(self):
super(MainWindow, self).__init__()
MainWindow._window_list.append(self)
self.setupUi(self)
# Qt Designer (at least to v4.2.1) can't handle arbitrary widgets in a
# QToolBar - even though uic can, and they are in the original .ui
# file. Therefore we manually add the problematic widgets.
self.lblAddress = QLabel("Address", self.tbAddress)
self.tbAddress.insertWidget(self.actionGo, self.lblAddress)
self.addressEdit = QLineEdit(self.tbAddress)
self.tbAddress.insertWidget(self.actionGo, self.addressEdit)
self.addressEdit.returnPressed.connect(self.actionGo.trigger)
self.actionBack.triggered.connect(self.WebBrowser.GoBack)
self.actionForward.triggered.connect(self.WebBrowser.GoForward)
self.actionStop.triggered.connect(self.WebBrowser.Stop)
self.actionRefresh.triggered.connect(self.WebBrowser.Refresh)
self.actionHome.triggered.connect(self.WebBrowser.GoHome)
self.actionSearch.triggered.connect(self.WebBrowser.GoSearch)
self.pb = QProgressBar(self.statusBar())
self.pb.setTextVisible(False)
self.pb.hide()
self.statusBar().addPermanentWidget(self.pb)
self.WebBrowser.dynamicCall('GoHome()')
def closeEvent(self, e):
MainWindow._window_list.remove(self)
e.accept()
def on_WebBrowser_TitleChange(self, title):
self.setWindowTitle("Qt WebBrowser - " + title)
def on_WebBrowser_ProgressChange(self, a, b):
if a <= 0 or b <= 0:
self.pb.hide()
return
self.pb.show()
self.pb.setRange(0, b)
self.pb.setValue(a)
def on_WebBrowser_CommandStateChange(self, cmd, on):
if cmd == 1:
self.actionForward.setEnabled(on)
elif cmd == 2:
self.actionBack.setEnabled(on)
def on_WebBrowser_BeforeNavigate(self):
self.actionStop.setEnabled(True)
def on_WebBrowser_NavigateComplete(self, _):
self.actionStop.setEnabled(False)
@pyqtSlot()
def on_actionGo_triggered(self):
self.WebBrowser.dynamicCall('Navigate(const QString&)',
self.addressEdit.text())
@pyqtSlot()
def on_actionNewWindow_triggered(self):
window = MainWindow()
window.show()
if self.addressEdit.text().isEmpty():
return;
window.addressEdit.setText(self.addressEdit.text())
window.actionStop.setEnabled(True)
window.on_actionGo_triggered()
@pyqtSlot()
def on_actionAbout_triggered(self):
QMessageBox.about(self, "About WebBrowser",
"This Example has been created using the ActiveQt integration into Qt Designer.\n"
"It demonstrates the use of QAxWidget to embed the Internet Explorer ActiveX\n"
"control into a Qt application.")
@pyqtSlot()
def on_actionAboutQt_triggered(self):
QMessageBox.aboutQt(self, "About Qt")
示例15: OWLTranslationForm
# 需要导入模块: from PyQt5.QtWidgets import QProgressBar [as 别名]
# 或者: from PyQt5.QtWidgets.QProgressBar import setRange [as 别名]
class OWLTranslationForm(QDialog):
"""
This class implements the form used to perform Graphol -> OWL ontology translation.
"""
def __init__(self, scene, filepath, parent=None):
"""
Initialize the form dialog.
:type scene: DiagramScene
:type filepath: str
:type parent: QWidget
"""
super().__init__(parent)
self.scene = scene
self.filepath = filepath
self.worker = None
self.workerThread = None
self.iriField = StringField(self)
self.iriField.setFixedWidth(300)
self.iriField.setValidator(QRegExpValidator(QRegExp('[\w:\/\[\]=?%#~\.\-\+]*'), self))
self.prefixField = StringField(self)
self.prefixField.setFixedWidth(300)
self.prefixField.setValidator(QRegExpValidator(QRegExp('[\w]*'), self))
self.syntaxField = ComboBox(self)
for syntax in OWLSyntax:
self.syntaxField.addItem(syntax.value, syntax)
self.syntaxField.setCurrentIndex(0)
self.progressBar = QProgressBar(self)
self.progressBar.setAlignment(Qt.AlignHCenter)
self.progressBar.setRange(0, 100)
self.progressBar.setValue(0)
self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
self.buttonBox.button(QDialogButtonBox.Ok).setDisabled(True)
self.mainLayout = QFormLayout(self)
self.mainLayout.addRow('IRI', self.iriField)
self.mainLayout.addRow('Prefix', self.prefixField)
self.mainLayout.addRow('Syntax', self.syntaxField)
self.mainLayout.addRow(self.progressBar)
self.mainLayout.addRow(self.buttonBox)
self.setWindowTitle('OWL Translation')
self.setWindowIcon(QIcon(':/images/eddy'))
self.setFixedSize(self.sizeHint())
connect(self.buttonBox.accepted, self.run)
connect(self.buttonBox.rejected, self.reject)
connect(self.iriField.textChanged, self.iriChanged)
####################################################################################################################
# #
# SLOTS #
# #
####################################################################################################################
@pyqtSlot(Exception)
def errored(self, exception):
"""
Executed whenever the translation errors.
:type exception: Exception
"""
if isinstance(exception, MalformedDiagramError):
msgbox = QMessageBox(self)
msgbox.setIconPixmap(QPixmap(':/icons/warning'))
msgbox.setWindowIcon(QIcon(':/images/eddy'))
msgbox.setWindowTitle('Malformed Diagram')
msgbox.setText('Malformed expression detected on {}: {}'.format(exception.item, exception))
msgbox.setInformativeText('Do you want to see the error in the diagram?')
msgbox.setStandardButtons(QMessageBox.Yes|QMessageBox.No)
S = QSpacerItem(400, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)
L = msgbox.layout()
L.addItem(S, L.rowCount(), 0, 1, L.columnCount())
msgbox.exec_()
if msgbox.result() == QMessageBox.Yes:
for view in self.scene.views():
if isinstance(view, MainView):
view.centerOn(exception.item)
else:
msgbox = QMessageBox(self)
msgbox.setIconPixmap(QPixmap(':/icons/error'))
msgbox.setWindowIcon(QIcon(':/images/eddy'))
msgbox.setWindowTitle('Unhandled exception!')
msgbox.setStandardButtons(QMessageBox.Close)
msgbox.setText('Diagram translation could not be completed!')
msgbox.setInformativeText('Please <a href="{}">submit a bug report</a> with detailed information.'.format(BUG_TRACKER))
msgbox.setDetailedText(''.join(traceback.format_exception(type(exception), exception, exception.__traceback__)))
S = QSpacerItem(400, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)
L = msgbox.layout()
L.addItem(S, L.rowCount(), 0, 1, L.columnCount())
msgbox.exec_()
#.........这里部分代码省略.........