I am designing a timer with Qt. With QGraphicsEllipseItem, I drew a circle and now I need to animate the QPen around this circle (change color) every second. I found QGraphicsPathItem, but I need some examples on how to move forward. Can anyone show me an example?
You have two problems:
QGraphicsEllipseItem is not a QObject so QPropertyAnimation can't be used directly on this item
QGraphicsItemAnimation doesn't cover property you want to animate.
What you can do?
IMO best approach is to provide some custom QObject on which you could do this animation. You can inherit QObject or use fake QGraphicsObject (which is a QObject).
class ShapeItemPenAnimator : public QGraphicsObject {
Q_OBJECT
private:
QAbstractGraphicsShapeItem *mParent;
QPropertyAnimation *mAnimation;
public:
QPROPERTY(QColor penColor
READ penColor
WRITE setPenColor)
explicit ShapeItemPenAnimator(QAbstractGraphicsShapeItem * parent)
: QGraphicsObject(parent)
, mParent(parent) {
setFlags(QGraphicsItem::ItemHasNoContents);
mAnimation = new QPropertyAnimation(this, "penColor", this);
}
QColor penColor() const {
return mParent->pen().color();
}
public slots:
void setPenColor(const QColor &color) {
QPen pen(mParent->pen());
pen.setColor(color);
mParent->setPen(pen);
}
public:
void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0) {
}
QRectF boundingRect() const {
return QRectF();
}
QPropertyAnimation *animation() const {
return mAnimation;
}
}
Now you just attach this object to your QGraphicsEllipseItem and set animation you need.
// yourEllipse
ShapeItemPenAnimator *animator = new ShapeItemPenAnimator(yourEllipse);
animator->animation()->setEndValue(....);
animator->animation()->setStartValue(....);
animator->animation()->setDuration(....);
animator->animation()->setEasingCurve(....);
There are several classes helping with animations of QGraphicsItem in Qt. I suggest looking into QGraphicsItemAnimation and QPropertyAnimation. You can use the second one to animate the color of an item. Here is an example of using QPropertyAnimation:
How to make Qt widgets fade in or fade out?
Related
I was wondering if we could use properties to animate in a class which inherits QGraphicsSimpleTextItem?
I'm drawing this button :
It is made up of :
A circle, which inherits QGraphicsObject and override the geometry property
An ellipse, which basicaly is the same but takes the circle as a parent
A text, which inherits QObject and QGraphicsSimpleTextItem
For the first two, the animations works. But concerning the last one, I have the followings errors :
QPropertyAnimation: you're trying to animate a non-existing property localisation of your QObject
QPropertyAnimation: you're trying to animate a non-existing property localisation of your QObject
QPropertyAnimation: you're trying to animate a non-existing property sizePolicy of your QObject
QPropertyAnimation: you're trying to animate a non-existing property sizePolicy of your QObject
Here is my class 'MyText' :
class MyTextOk : public QObject, public QGraphicsSimpleTextItem
{
Q_PROPERTY(QPointF localisation READ localisation WRITE setLocalisation)
Q_PROPERTY(QFont sizePolicy READ sizePolicy WRITE setSizePolicy)
public:
explicit MyTextOk(QGraphicsObject *parent = 0);
~MyTextOk();
QPointF localisation() const;
void setLocalisation(const QPointF &value);
QFont sizePolicy() const;
void setSizePolicy(const QFont &value);
private:
QRectF boundingRect() const;
protected :
QPointF point;
QFont font;
};
And my .ccp
QVariant myFontInterpolator(const QFont &start, const QFont &end, qreal progress)
{
if (progress<0.5)
{
int a = (1-progress)*50 + progress*45;
QFont rt(start);
rt.setPointSize(a);
return rt;
}
else
{
int a = (1-progress)*45 + progress*50;
QFont rt(start);
rt.setPointSize(a);
return rt;
}
Q_UNUSED(end)
}
MyTextOk::MyTextOk(QGraphicsObject *parent)
: QObject(parent), QGraphicsSimpleTextItem(parent)
{
point = QPointF(-40,-45);
this->setText("Ok");
this->setPos(point);
this->setBrush(QBrush(Qt::white));
font = QFont("Colibri",50);
this->setFont(font);
qRegisterAnimationInterpolator<QFont>(myFontInterpolator);
}
MyTextOk::~MyTextOk()
{
}
QPointF MyTextOk::localisation() const
{
return point;
}
void MyTextOk::setLocalisation(const QPointF &value)
{
if(point!=value)
{
point = value;
update();
}
}
QFont MyTextOk::sizePolicy() const
{
return font;
}
void MyTextOk::setSizePolicy(const QFont &value)
{
if(font!=value)
{
font=value;
update();
}
}
QRectF MyTextOk::boundingRect() const
{
return QRectF(0,0,0,0);
}
And in my MainWindow I animate :
void MainWindow::lancerAnimBoutonRond()
{
animationBoutonRondTaille = new QPropertyAnimation(roundButton, "geometry");
animationBoutonRondTaille->setDuration(300);
animationBoutonRondTaille->setKeyValueAt(0, QRectF(-90, -90, 180, 180));
animationBoutonRondTaille->setKeyValueAt(0.5, QRectF(-85,-85,170,170));
animationBoutonRondTaille->setKeyValueAt(1, QRectF(-90, -90, 180, 180));
animationBoutonRondTaille -> start();
animationBoutonRondEllipse = new QPropertyAnimation(whiteShadow, "geometry");
animationBoutonRondEllipse->setDuration(300);
animationBoutonRondEllipse->setKeyValueAt(0,QRectF(-70,-80,140,80));
animationBoutonRondEllipse->setKeyValueAt(0.5,QRectF(-65,-75,130,90));
animationBoutonRondEllipse->setKeyValueAt(1,QRectF(-70,-80,140,80));
animationBoutonRondEllipse->start(); // These two work
animationBoutonRondOk = new QPropertyAnimation(textOk,"localisation");
animationBoutonRondOk->setDuration(300);
animationBoutonRondOk->setKeyValueAt(0,QPointF(-40,-45));
animationBoutonRondOk->setKeyValueAt(0.5,QPointF(-35, -40));
animationBoutonRondOk->setKeyValueAt(1,QPointF(-40, -45));
animationBoutonRondOk->start(); //error : QPropertyAnimation: you're trying to animate a non-existing property localisation of your QObject
animationBoutonRondOkTaille = new QPropertyAnimation(textOk,"sizePolicy");
animationBoutonRondOkTaille->setDuration(300);
animationBoutonRondOkTaille->setStartValue(QFont("Colibri",50));
animationBoutonRondOkTaille->setEndValue(QFont("Colibri",50));
animationBoutonRondOkTaille->start(); //error : 'QPropertyAnimation: you're trying to animate a non-existing property sizePolicy of your QObject'
}
I don't know if I can name my "own" properties, but I can't (?) override the font and pos properties since I inherits QGraphicsSimpleTextItem and use setFont() and setPos()
You can find all the code here if you want to try.
Thank you for your time.
Problem solved.
Q_OBJECT macro in the MyTextOk class definition was missing. After placing it, the code runs fine.
You can find a working example of my button here.
I have small problem with QOpenGLWidget and its background color.
When I want to create semi-transparent rect on my custom QOpenGLWidget using QPainter there are 2 different results:
If MyCustomWidget have parent - on every update rect's color multiplies (and after few repaints it is opaque, like previous painting result not cleaned)
If MyCustomWidget doesn't have parent - color doesn't repaints each time
Here is code example for QPainter:
class Widget : public QOpenGLWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0)
: QOpenGLWidget(parent)
{
resize(800, 600);
Test *test = new Test(this);
}
~Widget(){}
protected:
void paintEvent(QPaintEvent *) {}
protected:
void initializeGL() {
if(paintEngine()->type() != QPaintEngine::OpenGL &&
paintEngine()->type() != QPaintEngine::OpenGL2)
qDebug() << "ERROR. Type is: " << paintEngine()->type();
}
void resizeGL(int, int) {}
void paintGL() {
QPainter p;
p.begin(this);
{
p.fillRect(rect(), Qt::white);
}
p.end();
}
private:
class Test : public QOpenGLWidget
{
public:
Test(QWidget *parent = 0) : QOpenGLWidget(parent) {
resize(100, 100);
}
protected:
void paintEvent(QPaintEvent *) {
QPainter p(this);
p.fillRect(rect(), QColor(125, 125, 125, 255/10));
}
};
};
Also by default it has black background (I don't know how to fix it. setAttribute(Qt::WA_TranslucentBackground) doesn't helps).
Also, when I'm trying to clear color using glClear it ignores alpha (both on QOpenGLWidget with parent and not). Here is Test class from previous code, but now it is using opengl to clear color:
class Test : public QOpenGLWidget
{
public:
Test(QWidget *parent = 0) : QOpenGLWidget(parent) {
resize(100, 100);
}
void initializeGL() {
QOpenGLFunctions *f = context()->functions();
f->glClearColor(0.0f, 1.0f, 0.0f, 0.1f);
}
void paintGL() {
QOpenGLFunctions *f = context()->functions();
f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
};
How can I fix this problems?
I'm using Qt 5.5.0, Windows 10, MinGW 4.9.2
Xeed is correct when saying the QOpenGLWidget is painted first.
I'm not an expert but I think I found the solution. You need to set a widget attribute to always make the widget stacked on top (think of the widgets as layers on the window). Here is a link to where I got the following information:
P.S. As mentioned in the QQuickWidget post, there is a limitation regarding semi-transparency when using QQuickWidget or QOpenGLWidget as child widgets. For applications that absolutely need this, Qt 5.4 offers a workaround: the newly introduced Qt::WA_AlwaysStackOnTop widget attribute. This, at the expense of breaking the stacking order for other types of layouts, makes it possible to have a semi-transparent QQuickWidget or QOpenGLWidget with other widgets visible underneath. Of course, if the intention is only to make other applications on the desktop visible underneath, then the Qt::WA_TranslucentBackground attribute is sufficient
Solution in Python:
set attribute of OpenGL widget
setAttribute(Qt.WA_AlwaysStackOnTop)
Now the OpenGL widget is considered 'on top' in the window. Use 'glClearColor' function and specify the alpha channel to be zero (0.0).
glClearColor(0.0, 0.0, 0.0, 0.0)
I'm not sure how to write that in other languages but this worked for me. The OpenGL widget no longer has the default black background. It is transparent! Hope this helps.
As far as I know the QOpenGLWidget is always drawn first. Therefore you cannot show any widgets layered below. I'm currently looking into the same issue. I'll report back, when I find any solution.
I've had similar issue with QOpenGLWidget not repainting correctly in transparent areas and decided to switch to QOpenGLWindow wrapped inside QWidget::createWindowContainer()
I currently working on a text editor using Qtextedit and I want to Draw a shapes like triangle, square and ellipseā¦ etc in the editor to Richness the document.
So I was wondering if is it possible to do this with Qtextedit and only Qtextedit.
Actually I am new to Qt so any ideas any tutorial any links would be highly appreciated
Thanks in advance and sorry for my english.
Best regards.
Sure it's possible, if I understand you correctly. All you need is just implement your own TextEdit derived from QTextEdit and reimplement paintEvent()
For example:
QMyTextEdit.h
class QMyTextEdit : public QTextEdit
{
public:
QMyTextEdit(QWidget *parent = 0);
protected:
void paintEvent(QPaintEvent * event);
};
QMyTextEdit.cpp
QMyTextEdit::QMyTextEdit(QWidget *parent) :
QTextEdit(parent)
{
}
void QMyTextEdit::paintEvent(QPaintEvent *event)
{
QTextEdit::paintEvent(event);
QPainter painter(viewport());
QPen pen;
pen.setColor(Qt::blue);
pen.setWidth(2);
painter.setPen(pen);
painter.setRenderHint(QPainter::Antialiasing, true);
QPoint center = viewport()->rect().center();
painter.drawRect(center.x() - 10,center.y() - 10,20,20);
}
It's simple to draw line or ellipse just by using scene.addellipse(), etc.
QGraphicsScene scene(0,0,800,600);
QGraphicsView view(&scene);
scene.addText("Hello, world!");
QPen pen(Qt::green);
scene.addLine(0,0,200,200,pen);
scene.addEllipse(400,300,100,100,pen);
view.show();
now what should i do to set some pixel color? may i use a widget like qimage? by the way performance is an issue for me.thanks
I think that performing pixel manipulation on a QImage would slow down your application quite a lot. A good alternative is to subclasse QGraphicsItem in a new class, something like QGraphicsPixelItem, and implement the paint function like this:
// code untested
void QGraphicsPixelItem::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0)
{
painter->save();
foreach(const QPoint& p, pointList) {
// set your pen color etc.
painter->drawPoint(p);
}
painter->restore();
}
where pointList is some kind of container that you use to store the position of the pixels you want to draw.
I want to be able to paint on top of my application's window so that I can annotate all the widgets with some extra diagnostic information, similar to the CSS developer tools in Firefox (eg add widget classes, styles, highlight borders etc).
I can walk the widget tree and extract the relevant information, but the question is how can I overlay all the application windows with this information?
One way would be to override my QMainWindow's paint event, but this has to be done for all top level windows. Is there an alternative method where you can paint on the QDesktopWidget for instance? Or any hooks into each QWidget's paint method? Anything that involves subclassing QWidget itself won't work with the standard widgets.
This follows on from my previous question:
Are there any useful tools for diagnosing Qt layout and spacing problems?
cheers
Mandrill
EDIT:
Thanks to Dmitry I've now got a really simple method that is easily extensible:
class DiagnosticStyle : public QWindowsVistaStyle
{
Q_OBJECT
public:
typedef QWindowsVistaStyle BaseStyle;
void drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const;
};
void DiagnosticStyle::drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const
{
BaseStyle::drawControl(element, option, painter, widget);
if (widget && painter) {
// draw a border around the widget
painter->setPen(QColor("red"));
painter->drawRect(widget->rect());
// show the classname of the widget
QBrush translucentBrush(QColor(255,246,240, 100));
painter->fillRect(widget->rect(), translucentBrush);
painter->setPen(QColor("darkblue"));
painter->drawText(widget->rect(), Qt::AlignLeft | Qt::AlignVCenter, widget->metaObject()->className());
}
}
qApp->setStyle(new DiagnosticStyle());
You can create own style class based on QMotifStyle or other ... and paint on any widget/control related to him information.
void MyStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option,QPainter *painter, const QWidget *widget) const
{
QStyle::State flags = option->state;
QRect rect = option->rect;
QPalette pal = option->palette;
QBrush brush;
switch (element)
{
case PE_FrameTabWidget:
{
painter->save();
// for example: draw anything on TabWidget
painter->drawPixmap(rect,centerPm,centerPm.rect());
painter->restore();
}
break;
default:
QMotifStyle::drawPrimitive(element, option, painter, widget);
break;
}
}
Somewhere in Qt5 the styles (GTK, Windows, etc) were made internal. Now you need to use QCommonStyle.
If anyone's wondering how to do this with Qt5+. Here's a self-contained version of #the_mandrill's code above.
class DiagnosticStyle : public QCommonStyle
{
Q_OBJECT
public:
typedef QStyle BaseStyle;
void drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const
{
QCommonStyle::drawControl(element, option, painter, widget);
if (widget && painter) {
// draw a border around the widget
painter->setPen(QColor("red"));
painter->drawRect(widget->rect());
// show the classname of the widget
QBrush translucentBrush(QColor(255,246,240, 100));
painter->fillRect(widget->rect(), translucentBrush);
painter->setPen(QColor("darkblue"));
painter->drawText(widget->rect(), Qt::AlignLeft | Qt::AlignVCenter, widget->metaObject()->className());
}
};
};
Then, in your main window constructor call
qApp->setStyle(new DiagnosticStyle());