Qt, QTransform rotation - c++

I'm trying to draw text "on cylinder". It means, that I have five rows of text. Top row is rotated by the X axis for 10 degrees. The second for 5 degrees. The middle is not rotated at all. The four's row is rotated for -5 degrees. The five's is rotated for -10 degrees.
Rows 1, 2, 3 draws OK, but something is wrong with 4,5 rows. What am I doing wrong ?
I provides an image for understanding a problem and code snippet:
for( int i = 0; i < iterationsCount; ++i )
{
const QRect r( x2, y2, textWidth, itemHeight );
const QString text = sections.at( section ).values.at( index );
int rsc = 0;
p->save();
rsc = widgetHeight / 2 - y;
p->setTransform(QTransform().rotate(rsc, Qt::XAxis));
if( type == Section::DaySectionShort ||
type == Section::DaySectionLong )
{
QStringList values = text.split( QLatin1Char( ' ' ) );
p->setPen(
lighterColor( opt.palette.color( QPalette::WindowText ), 75 ) );
p->drawText( r, Qt::AlignLeft | Qt::TextSingleLine, values.at( 0 ) );
p->setPen( opt.palette.color( QPalette::WindowText ) );
p->drawText( r, Qt::AlignLeft | Qt::TextSingleLine, values.at( 1 ) );
}
else
{
p->drawText( r, Qt::AlignLeft | Qt::TextSingleLine, text );
}
p->setTransform(QTransform().rotate(-rsc, Qt::XAxis));
index = nextIndex( index, sections.at( section ).values.size() );
y += itemHeight + itemTopMargin;
p->restore();
}
My problem

As you have not provided a minimal complete code that reproduces the problem, I cannot guess what is wrong there. But the most probable reason is incorrect rsc calculation. At least the following draft works:
#include <QtCore>
#include <QtGui>
#include <QtWidgets>
class MyWidget: public QWidget
{
public:
MyWidget(QWidget *parent = nullptr)
: QWidget(parent)
{
QFont f = font();
f.setPointSize(15);
setFont(f);
}
protected:
void paintEvent(QPaintEvent *event) override
{
QWidget::paintEvent(event);
QPainter p(this);
const int itemHeight = fontMetrics().height();
const int itemTopMargin = 15;
const int xOffset = 15;
int y = itemHeight;
for (size_t i = 0; i < 5; ++i) {
// The angle is in range [-40, 40]. Remove " * 4" for [-10, 10].
const int rsc = (10 - 5 * i) * 4;
qDebug() << i << ":\t" << rsc << "\t" << y;
/*
Rotation must be performed relative to central point of the
drawn item. Transformations below are applied in reverse order.
At first translate item to make it's center in (0, 0). At
second rotate it relative to X axis. At third move the item to
desired position.
*/
QTransform transform;
transform.translate(xOffset, y + itemHeight / 2);
transform.rotate(rsc, Qt::XAxis);
transform.translate(0, - itemHeight / 2);
p.setTransform(transform);
p.drawText(QPoint(), QString("(Item no. %1)").arg(i + 1));
y += itemHeight + itemTopMargin;
}
}
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
MyWidget widget;
widget.setMaximumSize(200, 250);
widget.show();
return app.exec();
}
The transformation used here is complicated because of need to rotate each item relative to it's central y, not y = 0. This also may be the case.
Font and angles are increased to see considered effects better.

Related

QScrollArea - Resize content widgets by keeping the aspect ratio

I have a layout that looks like this.
Where:
Blue: rectangle it's a ScrollArea
Orange: rectangles are the widgets from that ScrollArea
My code:
#include <QtWidgets>
///////////////////////////////////////////////////////////////////////////////////////
class RoundedPolygon : public QPolygon {
public:
RoundedPolygon() { SetRadius(10); }
void SetRadius(unsigned int iRadius) { m_iRadius = iRadius; }
const QPainterPath &GetPath() {
m_path = QPainterPath();
if (count() < 3) {
qDebug() << "!! Polygon should have at least 3 points !!";
return m_path;
}
QPointF pt1;
QPointF pt2;
for (int i = 0; i < count(); i++) {
pt1 = GetLineStart(i);
if (i == 0)
m_path.moveTo(pt1);
else
m_path.quadTo(at(i), pt1);
pt2 = GetLineEnd(i);
m_path.lineTo(pt2);
}
// close the last corner
pt1 = GetLineStart(0);
m_path.quadTo(at(0), pt1);
return m_path;
}
private:
QPointF GetLineStart(int i) const {
QPointF pt;
QPoint pt1 = at(i);
QPoint pt2 = at((i + 1) % count());
float fRat = m_iRadius / GetDistance(pt1, pt2);
if (fRat > 0.5f)
fRat = 0.5f;
pt.setX((1.0f - fRat) * pt1.x() + fRat * pt2.x());
pt.setY((1.0f - fRat) * pt1.y() + fRat * pt2.y());
return pt;
}
QPointF GetLineEnd(int i) const {
QPointF pt;
QPoint pt1 = at(i);
QPoint pt2 = at((i + 1) % count());
float fRat = m_iRadius / GetDistance(pt1, pt2);
if (fRat > 0.5f)
fRat = 0.5f;
pt.setX(fRat * pt1.x() + (1.0f - fRat) * pt2.x());
pt.setY(fRat * pt1.y() + (1.0f - fRat) * pt2.y());
return pt;
}
float GetDistance(QPoint pt1, QPoint pt2) const {
int fD = (pt1.x() - pt2.x()) * (pt1.x() - pt2.x()) + (pt1.y() - pt2.y()) * (pt1.y() - pt2.y());
return sqrtf(fD);
}
private:
QPainterPath m_path;
unsigned int m_iRadius{};
};
class PolygonButtonWidget : public QWidget {
Q_OBJECT
public:
explicit PolygonButtonWidget(QWidget *parent = nullptr) : QWidget(parent) {}
~PolygonButtonWidget() override = default;
protected:
void resizeEvent(QResizeEvent *event) override {
float ratioW = 8;
float ratioH = 3;
// ui->scrollAreaWidgetContents->setFixedSize(5000, h);
float thisAspectRatio = (float) event->size().width() / event->size().height();
if (thisAspectRatio < ratioW / ratioH) {
float w = event->size().height() * ratioW / ratioH;
float h = event->size().height();
qDebug() << hasHeightForWidth() << " " << w << " " << h;
this->resize(w, h);
if (m_nrButtons != 0) {
this->move((w + 20) * m_nrButtons, this->y());
}
}
QWidget::resizeEvent(event);
}
int m_nrButtons{};
public:
void setMNrButtons(int mNrButtons) {
m_nrButtons = mNrButtons;
}
protected:
void paintEvent(QPaintEvent *event) override {
int offset = 50;
m_polygon.clear();
m_polygon.emplace_back(0, height()); //DOWN-LEFT
m_polygon.emplace_back(width() - offset, height()); //DOWN-RIGHT
m_polygon.emplace_back(width(), 0); //TOP-RIGHT
m_polygon.emplace_back(0 + offset, 0);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
RoundedPolygon poly;
poly.SetRadius(15);
for (QPoint point: m_polygon) {
poly << point;
}
QBrush fillBrush;
fillBrush.setColor(Qt::darkBlue);
fillBrush.setStyle(Qt::SolidPattern);
QPainterPath path;
path.addPath(poly.GetPath());
painter.fillPath(path, fillBrush);
}
void mousePressEvent(QMouseEvent *event) override {
auto cursorPos = mapFromGlobal(QCursor::pos());
qDebug() << "X: " << cursorPos.x() << " Y: " << cursorPos.y();
inside(cursorPos, m_polygon);
qDebug() << "Pressed";
}
private:
std::vector<QPoint> m_polygon;
bool inside(QPoint point, std::vector<QPoint> polygon) {
auto x = point.x();
auto y = point.y();
auto inside = false;
auto i = 0;
auto j = polygon.size() - 1;
while (i < polygon.size()) {
auto xi = polygon[i].x();
auto yi = polygon[i].y();
auto xj = polygon[j].x();
auto yj = polygon[j].y();
auto intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
j = i++;
}
qDebug() << inside;
return inside;
}
};
///////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWidget root;
QHBoxLayout layout{&root};
for (int i = 0; i < 10; ++i) {
auto p = new PolygonButtonWidget();
p->setMinimumSize(100, 100);
p->setMNrButtons(i);
layout.addWidget(p);
}
root.setStyleSheet("background-color: rgb(19,19,19);");
QScrollArea view;
view.setWidget(&root);
view.show();
app.exec();
}
#include "main.moc"
The problem arises when I'm trying to resize the window. In the moment of resizing, I want my widgets to keep their aspect ratio. But that's not going to happen.
I have scroll list of widgets which is looking like this (if it's expended on X way too much)
If I will scale it on Y-axis it's going to look like this.
After I've changed the resizeEvent now it's going to look something like this
or like this
How can I fix this? For some reason, some of my widgets are going to disappear, what should be my approach in order to fix this issue?
The problem is caused by the assumption that there's any mechanism that will automatically resize the widgets for you. There isn't. A QScrollArea acts as a layout barrier and any layouts inside of it are isolated from its size, and thus from any resize events.
You must resize the container widget (the one with blue outline on your diagram) yourself anytime the scroll area changes size, and you need first to prepare a test case for the widgets such that their size changes are properly managed when placed in the layout of your choice, and said layout is resized.
Finally, the pet peeve of mine: It's unlikely that you actually need the QMainWindow for anything. It's just a silly Qt Creator template. But unless you want an MDI interface and docking, you shouldn't be using the QMainWindow - and especially not when making a self-contained example. All you need here is QScrollArea as a top-level widget. That's literally all. Any QWidget can be a top-level window!
For future submissions, please provide all the code needed in a single main.cpp file that begins with #include <QtWidgets> and ends with #include "main.moc". You won't need any other includes for Qt classes, and you can write class definitions Java-style, with all the methods defined within the class declaration itself. This provides for short code - after all, a SO question isn't an Enterprise project. It's supposed to be minimal, and that really means that anything not necessary must be removed. No need for header files, multiple includes, nor other fluff - i.e. use Qt containers instead of C++ STL so that you don't need more includes etc.
Your example should look roughly as follows:
#include <QtWidgets>
class PolygonButtonWidget : public QAbstractButton {
Q_OBJECT
/* without seeing the code here, your question is unanswerable */
};
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
QWidget root;
QHBoxLayout layout{&root};
PolygonButtonWidget buttons[10];
for (auto &button : buttons)
layout.addWidget(&button);
QScrollArea view;
view.setWidget(&root);
view.show();
app.exec();
view.takeWidget();
}
#include "main.moc"
Without such an example, your question is hard to answer, since:
How can we debug it? Debugging means using a debugger. If your code cannot be immediately compiled, then it's quite unlikely that someone will bother debugging it, and debugging by inspection is often error-prone.
How can we provide a tested answer if we'd have to first write the entire "test case" for it?
How can we know what's inside your button widget? The behavior of that widget does affect the ultimate solution.
It'd also help if you described a few use cases that you'd expect to work. That is, mock up (with a drawing) the state of the widgets before and after the view is resized, so that we can easily see what it is that you expect to happen. A lot of it is very easy to miss when explaining your needs in words. Use cases are a lingua franca of software specifications. If you don't use them, it's highly likely that you yourself don't know what behavior you expect in all cases.

QtCharts - Background, foreground display

I want to display a QGraphicsRectItem in my QChartView. But the rectangle is displayed behind the lines series in the chart.
I've tried to do a setZValue(10), for example, on my QGraphicsRectItem and setZValue(0) on my QChart but it is still displayed behind.
Obviously I want the informations in the rectangle to be displayed in front of the series of the chart.
Constructor
StatisticsChartView::StatisticsChartView(QWidget *parent, QChart *chart)
: QChartView(chart, parent)
{
/* Create new chart */
_chart = new QChart();
chart = _chart;
_chart->setAnimationOptions(QChart::AllAnimations);
/* Default granularity */
m_iGranularity = DEFAULT_GRANULARITY;
/* Creating ellipse item which will display a circle when the mouse goes over the series */
m_ellipse = new QGraphicsEllipseItem(_chart);
penEllipse.setColor(QColor(0, 0, 0));
penBorder.setWidth(1);
m_ellipse->setPen(penEllipse);
/* Creating text item which will display the x and y value of the mouse position */
m_coordX = new QGraphicsSimpleTextItem(_chart);
m_coordY = new QGraphicsSimpleTextItem(_chart);
penBorder.setColor(QColor(0, 0, 0));
penBorder.setWidth(1);
m_coordX->setPen(penBorder);
m_coordY->setPen(penBorder);
m_rectHovered = new QGraphicsRectItem(_chart);
m_rectHovered->setBrush(QBrush(Qt::yellow));
m_coordHoveredX = new QGraphicsSimpleTextItem(m_rectHovered);
m_coordHoveredY = new QGraphicsSimpleTextItem(m_rectHovered);
penBorder.setColor(QColor(0, 0, 0));
penBorder.setWidth(1);
m_coordHoveredX->setPen(penBorder);
m_coordHoveredY->setPen(penBorder);
m_lineItemX = new QGraphicsLineItem(_chart);
m_lineItemY = new QGraphicsLineItem(_chart);
penLine.setColor(QColor(0, 0, 0));
penLine.setStyle(Qt::DotLine);
m_lineItemX->setPen(penLine);
m_lineItemY->setPen(penLine);
/* Enable zooming in the rectangle drawn with the left click of the mouse, zoom out with right click */
rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
mousePressed = 0;
seriesHovered = false;
setMouseTracking(true);
_chart->setAcceptHoverEvents(true);
_chart->setZValue(50);
m_ellipse->setZValue(10); //so it is displayed over the series
m_coordHoveredX->setZValue(20); //so it is displayed over others
setRenderHint(QPainter::Antialiasing);
setChart(_chart);
}
Creation of series
void StatisticsChartView::drawCurve(bool bDrawScale)
{
int w = WIDTH;
int h = HEIGHT;
/* Creating series */
QLineSeries *lineFalse = new QLineSeries();
QLineSeries *lineAutomatic = new QLineSeries();
QLineSeries *lineOk = new QLineSeries();
QLineSeries *lineFalsePositive = new QLineSeries();
QLineSeries *lineManualTreatement = new QLineSeries();
QLineSeries *lineFalseNegative = new QLineSeries();
QList<QLineSeries*> lineSeriesList;
lineSeriesList << lineFalse << lineAutomatic << lineOk << lineFalsePositive << lineManualTreatement << lineFalseNegative;
QList<QString> nameSeriesList;
nameSeriesList << "False" << "Automatic" << "Ok" << "FalsePositive" << "ManualTreatement" << "FalseNegative";
QList<QVector<GraphPoint>> graphPointList;
graphPointList << gpFalse << gpDetected << gpOk << gpDetectedNotOk << gpManualTreatement << gpFalseNegative;
double graphX = 100.0 / (m_iGranularity);
bool pointsVisible = true;
for (int n = 0; n < lineSeriesList.count(); ++n)
{
/* Adding points to line series */
for (int i = 0; i < m_iGranularity + 1; ++i)
{
lineSeriesList[n]->append(i * graphX, (float)(graphPointList[n][i]).fValue * 100);
lineSeriesList[n]->setPointsVisible(pointsVisible);
lineSeriesList[n]->setName(nameSeriesList[n]);
}
}
_chart->legend()->setVisible(true);
_chart->legend()->setAlignment(Qt::AlignBottom);
/* Setting axis X and Y */
axisX = new QValueAxis();
axisY = new QValueAxis();
axisX->setRange(0, 100);
axisY->setRange(0, 100);
/* Adding line series to the chart and attaching them to the same axis */
for (int j = 0; j < lineSeriesList.count(); ++j)
{
_chart->addSeries(lineSeriesList[j]);
_chart->setAxisX(axisX, lineSeriesList[j]);
_chart->setAxisY(axisY, lineSeriesList[j]);
connect(lineSeriesList[j], SIGNAL(hovered(QPointF, bool)), this, SLOT(onSeriesHovered(QPointF, bool)));
}
_chart->resize(w, h);
return;
}
Drawing rectangle on chart
void StatisticsChartView::onSeriesHovered(QPointF point, bool state)
{
seriesHovered = state;
/* Updating the size of the rectangle */
if (mousePressed == 0 && seriesHovered == true)
{
/* x and y position on the graph */
qreal x = _chart->mapToPosition(point).x();
qreal y = _chart->mapToPosition(point).y();
/* x and y value on the graph from 0 to 100 for ou graph */
qreal xVal = point.x();
qreal yVal = point.y();
qreal maxX = axisX->max();
qreal minX = axisX->min();
qreal maxY = axisY->max();
qreal minY = axisY->min();
/* We don't want to display value outside of the axis range */
if (xVal <= maxX && xVal >= minX && yVal <= maxY && yVal >= minY)
{
m_coordHoveredX->setVisible(true);
m_coordHoveredY->setVisible(true);
m_rectHovered->setVisible(true);
m_ellipse->setVisible(true);
m_rectHovered->setRect(x - 31, y - 31, 30, 30);
qreal rectX = m_rectHovered->rect().x();
qreal rectY = m_rectHovered->rect().y();
qreal rectW = m_rectHovered->rect().width();
qreal rectH = m_rectHovered->rect().height();
/* We're setting the labels and nicely adjusting to chart axis labels (adjusting so the dot lines are centered on the label) */
m_coordHoveredX->setPos(rectX + rectW / 4 - 3, rectY + 1);
m_coordHoveredY->setPos(rectX + rectW / 4 - 3, rectY + rectH / 2 + 1);
/* Setting value to displayed with four digit max, float, 1 decimal */
m_coordHoveredX->setText(QString("%1").arg(xVal, 4, 'f', 1, '0'));
m_coordHoveredY->setText(QString("%1").arg(yVal, 4, 'f', 1, '0'));
m_ellipse->setRect(QRectF::QRectF(x, y, 10, 10));
m_ellipse->setPos(x, y);
m_ellipse->setBrush(QBrush(Qt::red));
}
else
{
/* We're not displaying information if out of the chart */
m_coordHoveredX->setVisible(false);
m_coordHoveredY->setVisible(false);
m_rectHovered->setVisible(false);
m_ellipse->setVisible(false);
}
}
else
{
/* We're not displaying information if series aren't hovered */
m_coordHoveredX->setVisible(false);
m_coordHoveredY->setVisible(false);
m_rectHovered->setVisible(false);
m_ellipse->setVisible(false);
}
}
You should try using a series especially for your rectangle.
Setting it as the last series, on your chart, to be above the other lines. And adding a legend or a callout for the text.

Calculating view offset for zooming in at the position of the mouse cursor

I've got a "canvas" that the user can draw pixels, etc. onto. It works well, but my zoom functionality currently uses the same origin regardless of the position of the mouse. I'd like to implement functionality like that of Google Maps' zoom behaviour:
That is, the zoom's origin should always be the position of the mouse cursor.
What I currently have is not exactly right...
My attempts have mostly been stabs in the dark, but I've also tried using the code from this answer without success.
main.cpp:
#include <QGuiApplication>
#include <QtQuick>
class Canvas : public QQuickPaintedItem
{
Q_OBJECT
public:
Canvas() :
mTileWidth(25),
mTileHeight(25),
mTilesAcross(10),
mTilesDown(10),
mOffset(QPoint(400, 400)),
mZoomLevel(1)
{
}
void paint(QPainter *painter) override {
painter->translate(mOffset);
const int zoomedTileWidth = mTilesAcross * mZoomLevel;
const int zoomedTileHeight = mTilesDown * mZoomLevel;
const int zoomedMapWidth = qMin(mTilesAcross * zoomedTileWidth, qFloor(width()));
const int zoomedMapHeight = qMin(mTilesDown * zoomedTileHeight, qFloor(height()));
painter->fillRect(0, 0, zoomedMapWidth, zoomedMapHeight, QColor(Qt::gray));
for (int y = 0; y < mTilesDown; ++y) {
for (int x = 0; x < mTilesAcross; ++x) {
const QRect rect(x * zoomedTileWidth, y * zoomedTileHeight, zoomedTileWidth, zoomedTileHeight);
painter->drawText(rect, QString::fromLatin1("%1, %2").arg(x).arg(y));
}
}
}
protected:
void wheelEvent(QWheelEvent *event) override {
const int oldZoomLevel = mZoomLevel;
mZoomLevel = qMax(1, qMin(mZoomLevel + (event->angleDelta().y() > 0 ? 1 : -1), 30));
const QPoint cursorPosRelativeToOffset = event->pos() - mOffset;
if (mZoomLevel != oldZoomLevel) {
mOffset.rx() -= cursorPosRelativeToOffset.x();
mOffset.ry() -= cursorPosRelativeToOffset.y();
// Attempts based on https://stackoverflow.com/a/14085161/904422
// mOffset.setX((event->pos().x() * (mZoomLevel - oldZoomLevel)) + (mZoomLevel * -mOffset.x()));
// mOffset.setY((event->pos().y() * (mZoomLevel - oldZoomLevel)) + (mZoomLevel * -mOffset.y()));
// mOffset.setX((cursorPosRelativeToOffset.x() * (mZoomLevel - oldZoomLevel)) + (mZoomLevel * -mOffset.x()));
// mOffset.setY((cursorPosRelativeToOffset.y() * (mZoomLevel - oldZoomLevel)) + (mZoomLevel * -mOffset.y()));
update();
}
}
void keyReleaseEvent(QKeyEvent *event) override {
static const int panDistance = 50;
switch (event->key()) {
case Qt::Key_Left:
mOffset.rx() -= panDistance;
update();
break;
case Qt::Key_Right:
mOffset.rx() += panDistance;
update();
break;
case Qt::Key_Up:
mOffset.ry() -= panDistance;
update();
break;
case Qt::Key_Down:
mOffset.ry() += panDistance;
update();
break;
}
}
private:
const int mTileWidth;
const int mTileHeight;
const int mTilesAcross;
const int mTilesDown;
QPoint mOffset;
int mZoomLevel;
};
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<Canvas>("App", 1, 0, "Canvas");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
#include "main.moc"
main.qml:
import QtQuick 2.5
import QtQuick.Window 2.2
import App 1.0 as App
Window {
visible: true
width: 1200
height: 900
title: qsTr("Hello World")
Shortcut {
sequence: "Ctrl+Q"
onActivated: Qt.quit()
}
App.Canvas {
focus: true
anchors.fill: parent
}
}
What am I doing wrong in the wheelEvent() function?
You have a rectangle R = [x_0, x_0 + w] x [y_0, y_0 + h] with absolute coordinates. When you map it to a widget (another rectangle), you apply some transformation T to an area W of R. This transformation is linear with offset:
Values of a_x, b_x, a_y, b_y are calculated to satisfy some simple conditions, you have already done it.
You also have a cursor (x_c, y_c) in R. It's coordinates in W are T(x_c, y_c). Now you want to apply another transformation ,
changing scale coefficients a_x, a_y to known a_x', a_y' with following condition: you want your cursor to point at the same coordinates (x_c, y_c) in R. I.e. T'(x_c, y_c) = T(x_c, y_c) — the same point in relative coordinates points to the same position in absolute coordinates. We derive a system for unknown offsets b_x', b_y' with known rest values. It gives
Last work is to find (x_c, y_c) from widget cursor position (x_p, y_p) = T(x_c, y_c):
and to substitute it:
In your terms it is
mOffset = event->pos() - float(mZoomLevel) / float(oldZoomLevel) *
(event->pos() - mOffset);
If you want to zoom like Google maps then your origin must be at top-left corner of the image(lets say (x,y) = (0,0) and (width, height) = (100,100)) with initial zoomLevel 100.
If you want to zoom at point(40,20) with zoom Factor of 5% then,
the displacement can be calculated as-
newX = 40 - 40*(100.0/105)
newY = 20 - 20*(100.0/105)
newWidth = width - (100.0/105)
newHeight = height - (100.0/105)
then set newX, newY as your origin and change width, height to newWidth and newHeight.
By this implementation you'll be able to zoom at a particular point where the cursor is. But this implementation will not work when you move the cursor at some other positions.
I am also looking for that implementation.

Why ball1.boundingrect.center returns the same value as ball2.boundingrect.center?

I'm programming a physis simulation with circles.
Ball.cpp Code:
Ball::Ball()
{
angle = 0;
setRotation(angle);
//set the speed
speed = 5;
double StartX = 720;
double StartY = 80;
StartX = (qrand() % 800);
StartY = (qrand() % 400);
radius = 40;
setTransformOriginPoint(radius,radius);
setPos (StartX,StartY);
}
QRectF Ball::boundingRect() const
{
return QRect(0,0,2*radius,2*radius);
}
bool Ball:: circCollide(QList <QGraphicsItem *> items) {
QPointF c1 = mapToParent(this->boundingRect().center());
foreach (QGraphicsItem * t, items) {
Ball * CastBall = dynamic_cast<Ball *>(t);
if(CastBall)
{
QPointF t1 = mapToScene(CastBall->boundingRect().center());
double distance = QLineF(c1,t1).length();
double radius1 = this->boundingRect().width() / 2;
double radius2 = CastBall->boundingRect().width() / 2;
double radii = radius1 + radius2;
if ( distance <= radii )
{
// qDebug() << "true collision";
return true;
}
}
}
// qDebug() << "false collision";
return false;
}
I've got the problem that this string of code returns always the same values for the position of the center for both objects, (t1.x == c1.x , t1.y == c1.y) but this == CastBall returns false, so it wasn't the same object, it just has the same coordinates for the centerpoint of the boundingRect.
The coordinates are already equal before this function is called and that for all 3 objects I generate, although the sets always have a different value.
First I thought it was a problem because boundingRect is defined as a const, so I made this function in my class
QRectF Ball:: centerRect()
{
return QRect(0,0,2*radius,2*radius);
}
and just replaced every use of boundingRect with it (was no problem since I already cast it in the method), but it still returned the same value for both centers.
Im really at my wits end with this one and hope to find some help.
The problem was following: the center of the bounding rectangle was not mapped to the coordinates of the ball. Following statement should work:
mapToScene(mapToItem(castBall, castBall->boundingRect().center()));

Get intermediate color from a gradient

Say I have a liner gradient as shown:
QLinearGradient linearGrad(QPointF(0, 0), QPointF(0, 100));
linearGrad.setColorAt(1, Qt::red);
linearGrad.setColorAt(0.5, Qt::yellow);
linearGrad.setColorAt(0, Qt::green);
How to get the color of the point QPointF(0, 28.5) in this gradient?
Indeed I want to have this kind of color distribution to be able to choose intermediate colors. I don't care if it is done by using QLinearGradient or something else.
I store the colors of gradient in one QList and then compute with color interpolation.
QColor ColorGradient::getColor(double value)
{
qDebug()<< "ColorGradient::getColor:";
//Asume mGradientColors.count()>1 and value=[0,1]
double stepbase = 1.0/(mGradientColors.count()-1);
int interval=mGradientColors.count()-1; //to fix 1<=0.99999999;
for (int i=1; i<mGradientColors.count();i++)//remove begin and end
{
if(value<=i*stepbase ){interval=i;break;}
}
double percentage = (value-stepbase*(interval-1))/stepbase;
QColor color(interpolate(mGradientColors[interval],mGradientColors[interval-1],percentage));
return color;
}
QColor ColorGradient::interpolate(QColor start,QColor end,double ratio)
{
int r = (int)(ratio*start.red() + (1-ratio)*end.red());
int g = (int)(ratio*start.green() + (1-ratio)*end.green());
int b = (int)(ratio*start.blue() + (1-ratio)*end.blue());
return QColor::fromRgb(r,g,b);
}
Mason Zhang answer does work, and very well !
Let controlPoints() return a QMap<qreal,QColor>, with a key between 0.0 and 1.0.
Here is how i did (thanks to Mason Zhang)
QColor getColor(qreal key) const
{
// key must belong to [0,1]
key = Clip(key, 0.0, 1.0) ;
// directly get color if known
if(controlPoints().contains(key))
{
return controlPoints().value(key) ;
}
// else, emulate a linear gradient
QPropertyAnimation interpolator ;
const qreal granularite = 100.0 ;
interpolator.setEasingCurve(QEasingCurve::Linear) ;
interpolator.setDuration(granularite) ;
foreach( qreal key, controlPoints().keys() )
{
interpolator.setKeyValueAt(key, controlPoints().value(key)) ;
}
interpolator.setCurrentTime(key*granularite) ;
return interpolator.currentValue().value<QColor>() ;
}
There is only way to make it:
There is a static member in QPixmap class
QPixmap QPixmap::grabWindow( WId window, int x = 0, int y = 0, int width = -1, int height = -1 )
1) draw your gradient on your widget;
2) grab you widget's surface into pixmap using that function; WId can be received from QWidget::effectiveWinId ();
3) convert token pixmap into QImage (there is an constructor available);
4) int QImage::pixelIndex( int x, int y ) returns the pixel index at (x, y) in QImage's color table. In your case you must calculate percentage value from widget's height ( pWidget->height() / 100 * 28.5 ).
5) QRgb QImage::color( int i ) returns the color in the color table at index i.
So returned Color is the color you were seeking.
QVariantAnimation has the similar functionality, and QVariantAnimation::keyValueAt can return the value you need. You may step into the code of QVariantAnimation and see how keyValueAt works.