PDA

View Full Version : QGraphicsScene addText() - Set font colour?



Gavin Harper
10th April 2011, 13:36
I am using a QGraphicsScene to implement a mobile Splash Screen and I would like to use a dark background. The issue is that I cannot seem to change the font to anything but black.

This is my main():


int main(int argc, char *argv[])
{
QApplication app(argc, argv);

MediaLibrary mLib;

// Splash Screen
QGraphicsScene scene;

QLinearGradient lGrad(QPointF(100, 100), QPointF(200, 200));
lGrad.setColorAt(0, Qt::black);
lGrad.setColorAt(1, Qt::darkBlue);
scene.setBackgroundBrush(lGrad);
scene.addText("Media Library", QFont("Times", 30));

QGraphicsView view(&scene);
view.show();

QTimer::singleShot(2000, &view, SLOT(close()));
QTimer::singleShot(2000, &mLib, SLOT(show()));

return app.exec();
}

What would be the best practise for changing the font colour?

Thank you

Gavin Harper
11th April 2011, 04:53
I solved this by creating a dedicated widget and reimplementing paintEvent().

Incase anyone is seeking a similar solution (I did not find anything on Google relating to changing QGraphicsScene font colour), this is what I did:

splashscreen.h

#ifndef SPLASHSCREEN_H
#define SPLASHSCREEN_H

#include <QWidget>

#include <QPainter>

class SplashScreen : public QWidget
{
Q_OBJECT
public:
explicit SplashScreen(QWidget *parent = 0);

protected:
void paintEvent(QPaintEvent *pEvent); // Reimplement paintEvent() to allow access to QPainter

private:
// UI Elements
QPainter *painter;
};

#endif // SPLASHSCREEN_H

splashscreen.cpp

#include "splashscreen.h"

SplashScreen::SplashScreen(QWidget *parent) : QWidget(parent)
{
// Nothing required here
}

// Reimplemented paintEvent()
void SplashScreen::paintEvent(QPaintEvent *pEvent)
{
painter = new QPainter(this); // Initialise painter

QLinearGradient lGrad(QPointF(500, 350), QPointF(700, 400)); // Set a gradient background
lGrad.setColorAt(0, Qt::black);
lGrad.setColorAt(1, Qt::darkBlue);
painter->fillRect(0, 0, 800, 440, lGrad);

painter->setPen(Qt::white); // Add text
painter->drawText(320, 150, "Media Library v0.1");
painter->drawText(20, 400, "Gavin Harper (F8827)");
}

Aravinda
15th April 2011, 12:00
This way it works
(just change to your variables you need):


QGraphicsSimpleTextItem * simpleTextItem1 = graphicsScene->addSimpleText(QString("my text number%1").arg(i+1));
simpleTextItem1->setBrush(QColor(255, 255, 0, 127));
//you get yellow semitransparent (text) colour or whatever the colour you want