Related
So , I am trying to blink the push button with the color that I pass and between white. And it only seems to blink it so many times after that code would crash.
I have tried it to implement the blinking with different blink rates and it
would it still break at some time.
in 'a' I have the string like "Background-color: rgb(255,0,0)".
in 'timings' i have a list like[208, 280]or it could be [48,32,48,32,100,280], this represents the on and off timings 'zeroth index' represents on and 'index 1' represents off time and follows the pattern so on.
while True:
i = 0
while i < len(timings):
if self.p[2] == 1:
self.b.setStyleSheet("{}".format(a))
self.b.update()
time.sleep(timings[i]/1000)
self.b.setStyleSheet("Background-color: rgb(255,255,255)")
self.b.update()
time.sleep(timings[i+1]/1000)
i = i + 2
self.head1, self.head2, self.head3 all have list with some thing like this ["Background-color:rgb(255,0,0)",list of on and off patterns, head number#]
right now, I am working with three heads.
def flash(self):
obj1 = threads(self.head1, self.head1_pb)
obj2 = threads(self.head2, self.head2_pb)
obj3 = threads(self.head3, self.head3_pb)
obj1.start()
time.sleep(.02)
obj2.start()
time.sleep(.02)
obj3.start()
class threads(Thread):
def __init__(self, a, pb):
Thread.__init__(self)
self.p = a
self.b = pb
def run(self):
a = self.p[0]
timings = self.p[1]
print(timings[0])
while True:
i = 0
while i < len(timings):
if self.p[2] == 1:
self.b.setStyleSheet("{}".format(a))
self.b.update()
time.sleep(timings[i]/1000)
self.b.setStyleSheet("Background-color: rgb(255,255,255)")
self.b.update()
time.sleep(timings[i+1]/1000)
i = i + 2
elif self.p[2] == 2:
self.b.setStyleSheet("{}".format(a))
self.b.update()
time.sleep(timings[i]/1000)
self.b.setStyleSheet("Background-color: rgb(255,255,255)")
self.b.update()
time.sleep(timings[i+1]/1000)
i = i + 2
else:
self.b.setStyleSheet("{}".format(a))
self.b.update()
time.sleep(timings[i]/1000)
self.b.setStyleSheet("Background-color: rgb(255,255,255)")
self.b.update()
time.sleep(timings[i+1]/1000)
i = i + 2
You can change the color as many times as you want, the problem is that you should not use a time consuming loop or use time.sleep() because they block the eventloop generating the GUI to freeze. Instead, use a QTimer to call the task that changes color every so often.
In the following example, create a custom button that implements what you want:
from PySide2 import QtCore, QtGui, QtWidgets
class PushButton(QtWidgets.QPushButton):
def __init__(self, *args, **kwargs):
super(PushButton, self).__init__(*args, **kwargs)
self._color = QtGui.QColor("white")
timer_on = QtCore.QTimer(singleShot=True, timeout=self.on_timeout)
timer_off = QtCore.QTimer(singleShot=True, timeout=self.on_timeout)
self._timers = (timer_on, timer_off)
for timer, function in zip(self._timers, (self.on, self.off)):
timer.timeout.connect(function)
def setTime(self, on_time, off_time):
for t, timer in zip((on_time, off_time), self._timers):
timer.setInterval(t)
#QtCore.Slot()
def on_timeout(self):
timer = self.sender()
if timer not in self._timers:
return
timer_on, timer_off = self._timers
another_timer = timer_off if timer is timer_on else timer_on
another_timer.start()
def start(self):
timer_on, _ = self._timers
timer_on.start()
def stop(self):
for timer in self._timers:
timer.stop()
self.off()
def color(self):
return self._color
def setColor(self, color):
if self.color() == color:
return
self._color = color
def on(self):
self.setStyleSheet(
"""PushButton{ background-color: %s}""" % (self.color().name(),)
)
def off(self):
self.setStyleSheet(
"""PushButton{ background-color: rgb(255,255,255)}"""
)
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
button = PushButton()
button.setColor(QtGui.QColor("salmon"))
button.setTime(208, 280)
button.start()
# stop blink in 30 seconds
# QtCore.QTimer.singleShot(30 * 1000, button.stop)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(button)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setStyle("fusion")
w = Widget()
w.show()
sys.exit(app.exec_())
Plus:
As you note that you have a lot of data, it is best to create an iterator to save memory. Considering the above I have created a QPushButton that obtains the data from the iterator.
import random
from functools import partial
from PySide2 import QtCore, QtGui, QtWidgets
def generate_data():
i = 0
while i < 1000000:
color_on = random.randint(10, 500)
color_off = random.randint(10, 500)
color = QtGui.QColor(*random.sample(range(255), 3))
yield color_on, color_off, color
i += 1
class PushButton(QtWidgets.QPushButton):
def __init__(self, *args, **kwargs):
super(PushButton, self).__init__(*args, **kwargs)
self._color = QtGui.QColor("white")
self._generator = None
self.m_timer = QtCore.QTimer(
self, timeout=self.on_timeout, singleShot=True
)
def setGenerator(self, generator):
self._generator = generator
def start(self):
self.on_timeout()
#QtCore.Slot()
def on_timeout(self):
try:
time_on, time_off, color = next(self._generator)
self.setColor(color)
self.m_timer.start(time_on + time_off)
QtCore.QTimer.singleShot(
time_on, partial(self.setColor, QtGui.QColor("white"))
)
except StopIteration:
self.m_timer.stop()
def setColor(self, color):
self.setStyleSheet(
"""PushButton{ background-color: %s}""" % (color.name(),)
)
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
for _ in range(6):
button = PushButton()
button.setGenerator(generate_data())
button.start()
lay.addWidget(button)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setStyle("fusion")
w = Widget()
w.resize(320, 240)
w.show()
sys.exit(app.exec_())
How can I get the percentage representing the point clicked along a QPainterPath. For example say I have a line, like the image below, and a user clicks on the QPainterPath, represented by the red dot. I would like to log what percentage the point falls along the path. In this case it would print 0.75 since the point is located around 75%.
These are the known variables:
# QPainterPath
path = QPainterPath()
path.moveTo( QPointF(10.00, -10.00) )
path.cubicTo(
QPointF(114.19, -10.00),
QPointF(145.80, -150.00),
QPointF(250.00, -150.00)
)
# User Clicked Point
QPointF(187.00, -130.00)
Updated!
My goal is to give the user the ability to click on the path and insert a point. Below is the code i have so far. You'll see in the video that it appears to fail when adding points between points. simply click on the path to insert a point.
Video Link to Watch bug:
https://youtu.be/nlWyZUIa7II
import sys
from PySide.QtGui import *
from PySide.QtCore import *
import random, math
class MyGraphicsView(QGraphicsView):
def __init__(self):
super(MyGraphicsView, self).__init__()
self.setDragMode(QGraphicsView.RubberBandDrag)
self.setCacheMode(QGraphicsView.CacheBackground)
self.setHorizontalScrollBarPolicy( Qt.ScrollBarAlwaysOff )
self.setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOff )
def mousePressEvent(self, event):
item = self.itemAt(event.pos())
if event.button() == Qt.LeftButton and isinstance(item, ConnectionItem):
percentage = self.percentageByPoint(item.shape(), self.mapToScene(event.pos()))
item.addKnotByPercent(percentage)
event.accept()
elif event.button() == Qt.MiddleButton:
super(MyGraphicsView, self).mousePressEvent(event)
# connection methods
def percentageByPoint(self, path, point, precision=0.5, width=3.0):
percentage = -1.0
if path.contains(point):
t = 0.0
d = []
while t <=100.0:
d.append(QVector2D(point - path.pointAtPercent(t/100.0)).length())
t += precision
percentage = d.index(min(d))*precision
return percentage
class MyGraphicsScene(QGraphicsScene):
def __init__(self, parent):
super(MyGraphicsScene, self).__init__()
self.setBackgroundBrush(QBrush(QColor(50,50,50)))
class KnotItem(QGraphicsEllipseItem):
def __init__(self, parent=None,):
super(self.__class__, self).__init__(parent)
self.setAcceptHoverEvents(True)
self.setFlag(self.ItemSendsScenePositionChanges, True)
self.setFlag(self.ItemIsSelectable, True) # false
self.setFlag(self.ItemIsMovable, True) # false
self.setRect(-6, -6, 12, 12)
# Overrides
def paint(self, painter, option, widget=None):
painter.save()
painter.setRenderHint(QPainter.Antialiasing)
painter.setPen(QPen(QColor(30,30,30), 2, Qt.SolidLine))
painter.setBrush(QBrush(QColor(255,30,30)))
painter.drawEllipse(self.rect())
painter.restore()
def itemChange(self, change, value):
if change == self.ItemScenePositionHasChanged:
if self.parentItem():
self.parentItem().update()
return super(self.__class__, self).itemChange(change, value)
def boundingRect(self):
rect = self.rect()
rect.adjust(-1,-1,1,1)
return rect
class ConnectionItem(QGraphicsPathItem):
def __init__(self, startPoint, endPoint, parent=None):
super(ConnectionItem, self).__init__()
self._hover = False
self.setAcceptHoverEvents(True)
self.setFlag( QGraphicsItem.ItemIsSelectable )
self.setFlag(QGraphicsItem.ItemSendsScenePositionChanges, True)
self.setZValue(-100)
self.startPoint = startPoint
self.endPoint = endPoint
self.knots = []
self.update()
def getBezierPath(self, points=[], curving=1.0):
# Calculate Bezier Line
path = QPainterPath()
curving = 1.0 # range 0-1
if len(points) < 2:
return path
path.moveTo(points[0])
for i in range(len(points)-1):
startPoint = points[i]
endPoint = points[i+1]
# use distance as mult, closer the nodes less the bezier
dist = math.hypot(endPoint.x() - startPoint.x(), endPoint.y() - startPoint.y())
# multiply distance by 0.375
offset = dist * 0.375 * curving
ctrlPt1 = startPoint + QPointF(offset,0);
ctrlPt2 = endPoint + QPointF(-offset,0);
# print startPoint, ctrlPt1, ctrlPt2, endPoint
path.cubicTo(ctrlPt1, ctrlPt2, endPoint)
return path
def drawPath(self, pos=None):
# Calculate Bezier Line
points = [self.startPoint]
for k in self.knots:
points.append(k.scenePos())
points.append(self.endPoint)
path = self.getBezierPath(points)
self.setPath(path)
def update(self):
super(self.__class__, self).update()
self.drawPath()
def paint(self, painter, option, widget):
painter.setRenderHints( QPainter.Antialiasing | QPainter.SmoothPixmapTransform | QPainter.HighQualityAntialiasing, True )
pen = QPen(QColor(170,170,170), 2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)
if self.isSelected():
pen.setColor(QColor(255, 255, 255))
elif self.hover:
pen.setColor(QColor(255, 30, 30))
painter.setPen(pen)
painter.drawPath(self.path())
def shape(self):
'''
Description:
This is super important for creating a more accurate path used for
collision detection by cursor.
'''
qp = QPainterPathStroker()
qp.setWidth(15)
qp.setCapStyle(Qt.SquareCap)
return qp.createStroke(self.path())
def hoverEnterEvent(self, event):
self.hover = True
self.update()
super(self.__class__, self).hoverEnterEvent(event)
def hoverLeaveEvent(self, event):
self.hover = False
self.update()
super(self.__class__, self).hoverEnterEvent(event)
def addKnot(self, pos=QPointF(0,0)):
'''
Description:
Add not based on current location of cursor or inbetween points on path.
'''
knotItem = KnotItem(parent=self)
knotItem.setPos(pos)
self.knots.append(knotItem)
self.update()
def addKnotByPercent(self, percentage=0.0):
'''
Description:
The percentage value should be between 0.0 and 100.0. This value
determines the location of the point and it's index in the knots list.
'''
if percentage < 0.0 or percentage > 100.0:
return
# add item
pos = self.shape().pointAtPercent(percentage*.01)
knotItem = KnotItem(parent=self)
knotItem.setPos(pos)
index = int(len(self.knots) * (percentage*.01))
print len(self.knots), (percentage), index
self.knots.insert(index, knotItem)
self.update()
# properties
#property
def hover(self):
return self._hover
#hover.setter
def hover(self, value=False):
self._hover = value
self.update()
class MyMainWindow(QMainWindow):
def __init__(self):
super(MyMainWindow, self).__init__()
self.setWindowTitle("Test")
self.resize(800,600)
self.gv = MyGraphicsView()
self.gv.setScene(MyGraphicsScene(self))
self.btnReset = QPushButton('Reset')
lay_main = QVBoxLayout()
lay_main.addWidget(self.btnReset)
lay_main.addWidget(self.gv)
widget_main = QWidget()
widget_main.setLayout(lay_main)
self.setCentralWidget(widget_main)
self.populate()
# connect
self.btnReset.clicked.connect(self.populate)
def populate(self):
scene = self.gv.scene()
for x in scene.items():
scene.removeItem(x)
del x
con = ConnectionItem(QPointF(-150,150), QPointF(250,-150))
scene.addItem(con)
def main():
app = QApplication(sys.argv)
ex = MyMainWindow()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
A possible solution is to use pointAtPercent () that returns a given point a percentage and calculate the distance to the point and find the minimum index and multiply it by the step. But for this the search must be refined because the previous algorithm works for any point even if it is outside the path. The idea in this case is to use a QPainterPath with a certain area using QPainterPathStroker and verify if the point belongs, and if not the value is outside the QPainterPath.
C++
#include <QtGui>
static qreal percentageByPoint(const QPainterPath & path, const QPointF & p, qreal precision=0.5, qreal width=3.0){
qreal percentage = -1;
QPainterPathStroker stroker;
stroker.setWidth(width);
QPainterPath strokepath = stroker.createStroke(path);
if(strokepath.contains(p)){
std::vector<qreal> d;
qreal t=0.0;
while(t<=100.0){
d.push_back(QVector2D(p - path.pointAtPercent(t/100)).length());
t+= precision;
}
std::vector<qreal>::iterator result = std::min_element(d.begin(), d.end());
int j= std::distance(d.begin(), result);
percentage = j*precision;
}
return percentage;
}
int main(int argc, char *argv[])
{
Q_UNUSED(argc)
Q_UNUSED(argv)
QPainterPath path;
path.moveTo( QPointF(10.00, -10.00) );
path.cubicTo(
QPointF(114.19, -10.00),
QPointF(145.80, -150.00),
QPointF(250.00, -150.00)
);
// User Clicked Point
QPointF p(187.00, -130.00);
qreal percentage = percentageByPoint(path, p);
qDebug() << percentage;
return 0;
}
python:
def percentageByPoint(path, point, precision=0.5, width=3.0):
percentage = -1.0
stroker = QtGui.QPainterPathStroker()
stroker.setWidth(width)
strokepath = stroker.createStroke(path)
if strokepath.contains(point):
t = 0.0
d = []
while t <=100.0:
d.append(QtGui.QVector2D(point - path.pointAtPercent(t/100)).length())
t += precision
percentage = d.index(min(d))*precision
return percentage
if __name__ == '__main__':
path = QtGui.QPainterPath()
path.moveTo(QtCore.QPointF(10.00, -10.00) )
path.cubicTo(
QtCore.QPointF(114.19, -10.00),
QtCore.QPointF(145.80, -150.00),
QtCore.QPointF(250.00, -150.00)
)
point = QtCore.QPointF(187.00, -130.00)
percentage = percentageByPoint(path, point)
print(percentage)
Output:
76.5
Instead of implementing the logic in QGraphicsView, you must do it in the item, and then when you update the path, the points must be ordered with respect to the percentage.
import math
from PySide import QtCore, QtGui
from functools import partial
class MyGraphicsView(QtGui.QGraphicsView):
def __init__(self):
super(MyGraphicsView, self).__init__()
self.setDragMode(QtGui.QGraphicsView.RubberBandDrag)
self.setCacheMode(QtGui.QGraphicsView.CacheBackground)
self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
scene = QtGui.QGraphicsScene(self)
scene.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(50,50,50)))
self.setScene(scene)
class KnotItem(QtGui.QGraphicsEllipseItem):
def __init__(self, parent=None,):
super(self.__class__, self).__init__(parent)
self.setAcceptHoverEvents(True)
self.setFlag(self.ItemSendsScenePositionChanges, True)
self.setFlag(self.ItemIsSelectable, True)
self.setFlag(self.ItemIsMovable, True)
self.setRect(-6, -6, 12, 12)
self.setPen(QtGui.QPen(QtGui.QColor(30,30,30), 2, QtCore.Qt.SolidLine))
self.setBrush(QtGui.QBrush(QtGui.QColor(255,30,30)))
def itemChange(self, change, value):
if change == self.ItemScenePositionHasChanged:
if isinstance(self.parentItem(), ConnectionItem):
self.parentItem().updatePath()
# QtCore.QTimer.singleShot(60, partial(self.parentItem().setSelected,False))
return super(self.__class__, self).itemChange(change, value)
class ConnectionItem(QtGui.QGraphicsPathItem):
def __init__(self, startPoint, endPoint, parent=None):
super(ConnectionItem, self).__init__(parent)
self._start_point = startPoint
self._end_point = endPoint
self._hover = False
self.setAcceptHoverEvents(True)
self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable )
self.setFlag(QtGui.QGraphicsItem.ItemSendsScenePositionChanges)
self.setZValue(-100)
self.updatePath()
def updatePath(self):
p = [self._start_point]
for children in self.childItems():
if isinstance(children, KnotItem):
p.append(children.pos())
p.append(self._end_point)
v = sorted(p, key=partial(ConnectionItem.percentageByPoint, self.path()))
self.setPath(ConnectionItem.getBezierPath(v))
def paint(self, painter, option, widget):
painter.setRenderHints(QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform | QtGui.QPainter.HighQualityAntialiasing, True )
pen = QtGui.QPen(QtGui.QColor(170,170,170), 2, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin)
if self.isSelected():
pen.setColor(QtGui.QColor(255, 255, 255))
elif self._hover:
pen.setColor(QtGui.QColor(255, 30, 30))
painter.setPen(pen)
painter.drawPath(self.path())
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
item = KnotItem(parent=self)
item.setPos(event.pos())
def hoverEnterEvent(self, event):
self._hover = True
self.update()
super(self.__class__, self).hoverEnterEvent(event)
def hoverLeaveEvent(self, event):
self._hover = False
self.update()
super(self.__class__, self).hoverEnterEvent(event)
def shape(self):
qp = QtGui.QPainterPathStroker()
qp.setWidth(15)
qp.setCapStyle(QtCore.Qt.SquareCap)
return qp.createStroke(self.path())
#staticmethod
def getBezierPath(points=[], curving=1.0):
# Calculate Bezier Line
path = QtGui.QPainterPath()
curving = 1.0 # range 0-1
if len(points) < 2:
return path
path.moveTo(points[0])
for i in range(len(points)-1):
startPoint = points[i]
endPoint = points[i+1]
# use distance as mult, closer the nodes less the bezier
dist = math.hypot(endPoint.x() - startPoint.x(), endPoint.y() - startPoint.y())
# multiply distance by 0.375
offset = dist * 0.375 * curving
ctrlPt1 = startPoint + QtCore.QPointF(offset,0);
ctrlPt2 = endPoint + QtCore.QPointF(-offset,0);
# print startPoint, ctrlPt1, ctrlPt2, endPoint
path.cubicTo(ctrlPt1, ctrlPt2, endPoint)
return path
#staticmethod
def percentageByPoint(path, point, precision=0.5):
t = 0.0
d = []
while t <=100.0:
d.append(QtGui.QVector2D(point - path.pointAtPercent(t/100.0)).length())
t += precision
percentage = d.index(min(d))*precision
return percentage
class MyMainWindow(QtGui.QMainWindow):
def __init__(self):
super(MyMainWindow, self).__init__()
central_widget = QtGui.QWidget()
self.setCentralWidget(central_widget)
button = QtGui.QPushButton("Reset")
self._view = MyGraphicsView()
button.clicked.connect(self.reset)
lay = QtGui.QVBoxLayout(central_widget)
lay.addWidget(button)
lay.addWidget(self._view)
self.resize(640, 480)
self.reset()
#QtCore.Slot()
def reset(self):
self._view.scene().clear()
it = ConnectionItem(QtCore.QPointF(-150,150), QtCore.QPointF(250,-150))
self._view.scene().addItem(it)
def main():
import sys
app =QtGui.QApplication(sys.argv)
ex = MyMainWindow()
ex.show()
sys.exit(app.exec_())
main()
I want to show a spinner while a task is being performed in my pyqt5 application. I found this nice implementation of a spinner, so I tried it: https://github.com/z3ntu/QtWaitingSpinner
The demo works ok, but in the demo the spinner is shown into an empty area of the dialog. I would like it to be an overlay which covers the whole dialog.
The author of QtWaitingSpinner suggests that "As an alternative example, the code below will create a spinner that (1) blocks all user input to the main application for as long as the spinner is active, (2) automatically centers itself on its parent widget every time "start" is called and (3) makes use of the default shape, size and color settings." with the following code:
spinner = QtWaitingSpinner(self, True, True, Qt.ApplicationModal)
spinner.start() # starts spinning
But I tried this implementation as an example, and it didn't work:
from PyQt5.QtWidgets import QApplication, QDialog, QTabWidget, QWidget, QGroupBox, QPushButton, QVBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
import requests
import urllib
from waitingspinnerwidget import QtWaitingSpinner
class DownloadDataDialog(QDialog):
def __init__(self, parent=None):
super(DownloadDataDialog, self).__init__(parent)
self.spinner = QtWaitingSpinner(self, True, True, Qt.ApplicationModal)
tabWidget = QTabWidget(self)
tabWidget.addTab(MyTab(tabWidget), "MyTab")
mainLayout = QVBoxLayout()
mainLayout.addWidget(tabWidget)
self.setLayout(mainLayout)
self.setWindowTitle("Download option chain data from web")
class MyTab(QWidget):
def __init__(self, parent=None):
super(MyTab, self).__init__(parent)
dataGroup = QGroupBox('Data')
getButton = QPushButton('Download')
getButton.clicked.connect(self.download_data)
dataLayout = QVBoxLayout()
dataLayout.addWidget(getButton)
dataGroup.setLayout(dataLayout)
mainLayout = QVBoxLayout()
mainLayout.addWidget(dataGroup)
mainLayout.addStretch(1)
self.setLayout(mainLayout)
def download_data(self):
self.parent().parent().parent().spinner.start()
url = 'http://www.meff.es/docs/Ficheros/Descarga/dRV/RV180912.zip'
filepath = None
try:
filepath = self.download_data_file(url)
except Exception as e:
print(e)
self.parent().parent().parent().spinner.stop()
if filepath:
#TODO doing stuff here
self.parent().parent().parent().close()
else:
pass #TODO show error dialog
def download_data_file(self, download_url):
# Build request URL and download the file
destination = 'test.zip'
urllib.request.urlretrieve(download_url, destination)
return destination
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
tabdialog = DownloadDataDialog()
tabdialog.show()
sys.exit(app.exec_())
So my intention is creating an invisible layer, setting the spinner as its only widget, and showing the translucid layer over the whole dialog window.
Any idea of how I should do that?
Once I also had that problem so I modified the library, first activate the flags: QtCore.Qt.Dialog | QtCore.Qt.FramelessWindowHint, and the other change must be done in updatePosition() method:
def updatePosition(self):
if self.parentWidget() and self._centerOnParent:
parentRect = QtCore.QRect(self.parentWidget().mapToGlobal(QtCore.QPoint(0, 0)), self.parentWidget().size())
self.move(QtWidgets.QStyle.alignedRect(QtCore.Qt.LeftToRight, QtCore.Qt.AlignCenter, self.size(), parentRect).topLeft())
The result is as follows:
waitingspinnerwidget.py
import math
from PyQt5 import QtCore, QtGui, QtWidgets
class QtWaitingSpinner(QtWidgets.QWidget):
def __init__(self, parent=None, centerOnParent=True, disableParentWhenSpinning=False, modality=QtCore.Qt.NonModal):
super().__init__(parent, flags=QtCore.Qt.Dialog | QtCore.Qt.FramelessWindowHint)
self._centerOnParent = centerOnParent
self._disableParentWhenSpinning = disableParentWhenSpinning
# WAS IN initialize()
self._color = QtGui.QColor(QtCore.Qt.black)
self._roundness = 100.0
self._minimumTrailOpacity = 3.14159265358979323846
self._trailFadePercentage = 80.0
self._revolutionsPerSecond = 1.57079632679489661923
self._numberOfLines = 20
self._lineLength = 10
self._lineWidth = 2
self._innerRadius = 10
self._currentCounter = 0
self._isSpinning = False
self._timer = QtCore.QTimer(self)
self._timer.timeout.connect(self.rotate)
self.updateSize()
self.updateTimer()
self.hide()
# END initialize()
self.setWindowModality(modality)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
def paintEvent(self, QPaintEvent):
self.updatePosition()
painter = QtGui.QPainter(self)
painter.fillRect(self.rect(), QtCore.Qt.transparent)
painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
if self._currentCounter >= self._numberOfLines:
self._currentCounter = 0
painter.setPen(QtCore.Qt.NoPen)
for i in range(0, self._numberOfLines):
painter.save()
painter.translate(self._innerRadius + self._lineLength, self._innerRadius + self._lineLength)
rotateAngle = float(360 * i) / float(self._numberOfLines)
painter.rotate(rotateAngle)
painter.translate(self._innerRadius, 0)
distance = self.lineCountDistanceFromPrimary(i, self._currentCounter, self._numberOfLines)
color = self.currentLineColor(distance, self._numberOfLines, self._trailFadePercentage,
self._minimumTrailOpacity, self._color)
painter.setBrush(color)
painter.drawRoundedRect(QtCore.QRect(0, -self._lineWidth / 2, self._lineLength, self._lineWidth), self._roundness,
self._roundness, QtCore.Qt.RelativeSize)
painter.restore()
def start(self):
self.updatePosition()
self._isSpinning = True
self.show()
if self.parentWidget and self._disableParentWhenSpinning:
self.parentWidget().setEnabled(False)
if not self._timer.isActive():
self._timer.start()
self._currentCounter = 0
def stop(self):
self._isSpinning = False
self.hide()
if self.parentWidget() and self._disableParentWhenSpinning:
self.parentWidget().setEnabled(True)
if self._timer.isActive():
self._timer.stop()
self._currentCounter = 0
def setNumberOfLines(self, lines):
self._numberOfLines = lines
self._currentCounter = 0
self.updateTimer()
def setLineLength(self, length):
self._lineLength = length
self.updateSize()
def setLineWidth(self, width):
self._lineWidth = width
self.updateSize()
def setInnerRadius(self, radius):
self._innerRadius = radius
self.updateSize()
def color(self):
return self._color
def roundness(self):
return self._roundness
def minimumTrailOpacity(self):
return self._minimumTrailOpacity
def trailFadePercentage(self):
return self._trailFadePercentage
def revolutionsPersSecond(self):
return self._revolutionsPerSecond
def numberOfLines(self):
return self._numberOfLines
def lineLength(self):
return self._lineLength
def lineWidth(self):
return self._lineWidth
def innerRadius(self):
return self._innerRadius
def isSpinning(self):
return self._isSpinning
def setRoundness(self, roundness):
self._roundness = max(0.0, min(100.0, roundness))
def setColor(self, color=QtCore.Qt.black):
self._color = QColor(color)
def setRevolutionsPerSecond(self, revolutionsPerSecond):
self._revolutionsPerSecond = revolutionsPerSecond
self.updateTimer()
def setTrailFadePercentage(self, trail):
self._trailFadePercentage = trail
def setMinimumTrailOpacity(self, minimumTrailOpacity):
self._minimumTrailOpacity = minimumTrailOpacity
def rotate(self):
self._currentCounter += 1
if self._currentCounter >= self._numberOfLines:
self._currentCounter = 0
self.update()
def updateSize(self):
size = (self._innerRadius + self._lineLength) * 2
self.setFixedSize(size, size)
def updateTimer(self):
self._timer.setInterval(1000 / (self._numberOfLines * self._revolutionsPerSecond))
def updatePosition(self):
if self.parentWidget() and self._centerOnParent:
parentRect = QtCore.QRect(self.parentWidget().mapToGlobal(QtCore.QPoint(0, 0)), self.parentWidget().size())
self.move(QtWidgets.QStyle.alignedRect(QtCore.Qt.LeftToRight, QtCore.Qt.AlignCenter, self.size(), parentRect).topLeft())
def lineCountDistanceFromPrimary(self, current, primary, totalNrOfLines):
distance = primary - current
if distance < 0:
distance += totalNrOfLines
return distance
def currentLineColor(self, countDistance, totalNrOfLines, trailFadePerc, minOpacity, colorinput):
color = QtGui.QColor(colorinput)
if countDistance == 0:
return color
minAlphaF = minOpacity / 100.0
distanceThreshold = int(math.ceil((totalNrOfLines - 1) * trailFadePerc / 100.0))
if countDistance > distanceThreshold:
color.setAlphaF(minAlphaF)
else:
alphaDiff = color.alphaF() - minAlphaF
gradient = alphaDiff / float(distanceThreshold + 1)
resultAlpha = color.alphaF() - gradient * countDistance
# If alpha is out of bounds, clip it.
resultAlpha = min(1.0, max(0.0, resultAlpha))
color.setAlphaF(resultAlpha)
return color
With the above we solve one of those problems, the other problem is that urllib.request.urlretrieve() is blocking so it will cause the GUI to freeze, so the solution is to move it to another thread, using a previous response we can do it in the following way:
from PyQt5 import QtCore, QtGui, QtWidgets
import urllib.request
from waitingspinnerwidget import QtWaitingSpinner
class RequestRunnable(QtCore.QRunnable):
def __init__(self, url, destination, dialog):
super(RequestRunnable, self).__init__()
self._url = url
self._destination = destination
self.w = dialog
def run(self):
urllib.request.urlretrieve(self._url, self._destination)
QMetaObject.invokeMethod(self.w, "FinishedDownload", QtCore.Qt.QueuedConnection)
class DownloadDataDialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super(DownloadDataDialog, self).__init__(parent)
self.spinner = QtWaitingSpinner(self, True, True, QtCore.Qt.ApplicationModal)
tabWidget = QtWidgets.QTabWidget(self)
tabWidget.addTab(MyTab(), "MyTab")
mainLayout = QtWidgets.QVBoxLayout(self)
mainLayout.addWidget(tabWidget)
self.setWindowTitle("Download option chain data from web")
class MyTab(QtWidgets.QWidget):
def __init__(self, parent=None):
super(MyTab, self).__init__(parent)
dataGroup = QtWidgets.QGroupBox('Data')
getButton = QtWidgets.QPushButton('Download')
getButton.clicked.connect(self.download_data)
dataLayout = QtWidgets.QVBoxLayout(self)
dataLayout.addWidget(getButton)
mainLayout = QtWidgets.QVBoxLayout(self)
mainLayout.addWidget(dataGroup)
mainLayout.addStretch(1)
def download_data(self):
self.parentWidget().window().spinner.start()
url = 'http://www.meff.es/docs/Ficheros/Descarga/dRV/RV180912.zip'
destination = 'test.zip'
runnable = RequestRunnable(url, destination, self)
QtCore.QThreadPool.globalInstance().start(runnable)
#QtCore.pyqtSlot()
def FinishedDownload(self):
self.parentWidget().window().spinner.stop()
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
tabdialog = DownloadDataDialog()
tabdialog.show()
sys.exit(app.exec_())
I need to adjust verticalScrollBar() on mouse wheel event. Trying to get the same behavior as horisontalScrollBar(). I mean it should remain in center of vertical scroll area.
Here is the code:
#!/usr/bin/env python
from PySide.QtGui import *
class windowClass(QWidget):
def __init__(self):
super(windowClass, self).__init__()
self.ly = QVBoxLayout(self)
self.view = viewClass()
self.ly.addWidget(self.view)
self.resize(500, 200)
class sceneClass(QGraphicsScene):
def __init__(self):
super(sceneClass, self).__init__()
self.setSceneRect(-1000, -1000, 2000, 2000)
self.grid = 30
class viewClass(QGraphicsView):
def __init__(self):
super(viewClass, self).__init__()
self.setDragMode(QGraphicsView.RubberBandDrag)
# self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
# self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.s = sceneClass()
self.setScene(self.s)
self.scaleY = 1
self.scaleX = 1
def wheelEvent(self, event):
self.setSceneScale(event.delta())
super(viewClass, self).wheelEvent(event)
def setSceneScale(self, delta):
if delta > 0:
self.scale(self.scaleX + 0.1, self.scaleY + 0.1)
else:
self.scale(self.scaleX - 0.1, self.scaleY - 0.1)
if __name__ == '__main__':
app = QApplication([])
w = windowClass()
w.show()
app.exec_()
As you can see I already used setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) but it did not worked because it just hides scroll bars
I've got the answer.
In constructor of QGraphicsView :
self.vscr = (self.size().height()/2)*-1
In wheelEvent :
self.verticalScrollBar().setValue(self.vscr)
I have problem with PySide (I'm still rookie in programming). I created custom QGraphicsItem called RBNode. It should stay in the position where mouseReleaseEvent has happend. I don't know why but when I'm trying to move the instance of RBNode class more than once, the position of this instance resets. How can I avoid reseting position?
Thanks in advance for your help.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PySide.QtGui import *
from PySide.QtCore import *
class RBNode(QGraphicsItem):
def __init__(self, factorView = None):
super(RBNode, self).__init__()
self.factor = factorView
self.pressed = False
self.x = self.pos().x()
self.y = self.pos().y()
self.setFlag(QGraphicsItem.ItemIsMovable)
def boundingRect(self):
return QRectF(-50,-50,100,100)
def paint(self, painter, option, widget):
rect = QRectF(-50,-50,100,100)
if self.pressed:
painter.setBrush(Qt.red)
else:
painter.setBrush(Qt.darkGray)
painter.drawEllipse(rect)
def mousePressEvent(self, event):
self.pressed = True
self.update()
QGraphicsItem.mousePressEvent(event)
def mouseReleaseEvent(self, event):
self.pressed = False
self.update()
QGraphicsItem.mouseReleaseEvent(event)
class RBGraphicView(QGraphicsView):
def __init__(self):
super(RBGraphicView, self).__init__()
self.factorView = 1
self.initScene()
self.initGui()
def initGui(self):
self.setWindowTitle("A Simple Animation")
self.show()
def initScene(self):
self.rbScene = QGraphicsScene(self)
self.rbAddItem(self.rbScene)
self.setScene(self.rbScene)
def rbAddItem(self, scene):
rbNode1 = RBNode(self.factorView)
rbNode1.setPos(100,100)
scene.addItem(rbNode1)
if __name__ == '__main__':
try:
myApp = QApplication(sys.argv)
myView = RBGraphicView()
myApp.exec_()
sys.exit(0)
except NameError:
print("Name Error:", sys.exc_info()[1])
except SystemExit:
print("Closing Window...")
except Exception:
print(sys.exc_info()[1])
You forgot self as parameter in the calls to mousePressEvent, mouseReleaseEvent of the super classes.
QGraphicsItem.mousePressEvent(self, event)
QGraphicsItem.mouseReleaseEvent(self, event)