Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML gradients with an orientation

QML gradient allows only from top to bottom in a Rectangle. The documentation says that it has to be done through combination of rotation and clipping.

I have just started learning QML (and little experience with HTML/CSS). Here is my code which I think can be improved for a lot better:

import QtQuick 1.0

Rectangle {
    width: 400; height: 400;

    Rectangle {
    width: 567; height: 567;

    gradient: Gradient {
            GradientStop {
        position: 0.0;
        color: "white";
        }
            GradientStop {
        position: 1.0;
        color: "blue";
        }
    }
    x: 116.5;
    transformOrigin: Item.Top;
    rotation: 45.0;
    }
}

Can you please suggest what are the better ways to do this?

like image 327
Xolve Avatar asked Apr 09 '12 18:04

Xolve


2 Answers

The Qt Graphical Effects module introduced in Qt 5.1 provides three gradient types. With the LinearGradient item (effect) it is no longer necessary to apply rotation in order to achieve e.g. a horizontal color gradient.
In particular by means of the start and end point (attributes) of LinearGradient any gradient direction is possible.

The following code implements a 45° angle (as proposed in the original post) by starting top right with white and ending bottom left with black:

import QtQuick 2.0
import QtGraphicalEffects 1.0

Item {
    id:myItem
    width: 300
    height: 300

    LinearGradient {
        anchors.fill: parent
        start: Qt.point(myItem.width, 0)
        end: Qt.point(0, myItem.height)
        gradient: Gradient {
            GradientStop { position: 0.0; color: "white" }
            GradientStop { position: 1.0; color: "black" }
        }
    }
}
like image 60
StefanQ Avatar answered Sep 29 '22 03:09

StefanQ


I'm afraid the documentation is correct. The only other way I can think of is to write a custom QML component in C++ which does what you want.

If you have Qt/C++ knowledge you could start here:

  • http://doc.qt.nokia.com/4.7-snapshot/qml-extending.html
  • http://doc.qt.nokia.com/4.7-snapshot/declarative-tutorials-extending-chapter1-basics.html

The Rectangle could be a good template or base class:

  • http://qt.gitorious.org/qt/qt/blobs/4.8/src/declarative/graphicsitems/qdeclarativerectangle_p.h
like image 29
blakharaz Avatar answered Sep 29 '22 02:09

blakharaz