QT Quick Designer Custom Components are Blank? - qt

I'm doing some testing of QT Quick to see if i can use it as a GUI replacement for the old Ui files. I noticed in some of the examples that custom components will populate the library view. I managed to do that (apparently they must be in a sub dir of the qml file that uses them?). However these components do not render in the Qt Quick design window. There is actually nothing to grab or manipulate. Upon running the program, they render correctly.
Does anyone have a solution? My source is below
import QtQuick 1.0
import Chips 1.0
Item {
width: 100
height: 62
Chip
{
}
}
chip.cpp
#include "Chip.h"
#include <QtGui>
Chip::Chip(QDeclarativeItem *parent)
: QDeclarativeItem(parent)
{
x = 0;
y = 0;
color = QColor(0, 200, 0);
setFlags(ItemIsSelectable | ItemIsMovable);
setFlag(QGraphicsItem::ItemHasNoContents, false);
setAcceptsHoverEvents(true);
}
//Chip::Chip(const QColor &color, int x, int y, QDeclarativeItem *parent)
// : QDeclarativeItem(parent)
//{
// this->x = x;
// this->y = y;
// this->color = color;
// setZValue((x + y) % 2);
// setFlags(ItemIsSelectable | ItemIsMovable);
// setFlag(QGraphicsItem::ItemHasNoContents, false);
// setAcceptsHoverEvents(true);
//}
QRectF Chip::boundingRect() const
{
return QRectF(0, 0, 110, 70);
}
QPainterPath Chip::shape() const
{
QPainterPath path;
path.addRect(14, 14, 82, 42);
return path;
}
void Chip::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(widget);
QColor fillColor = (option->state & QStyle::State_Selected) ? color.dark(150) : color;
if (option->state & QStyle::State_MouseOver)
fillColor = fillColor.light(125);
const qreal lod = option->levelOfDetailFromTransform(painter->worldTransform());
if (lod < 0.2) {
if (lod < 0.125) {
painter->fillRect(QRectF(0, 0, 110, 70), fillColor);
return;
}
QBrush b = painter->brush();
painter->setBrush(fillColor);
painter->drawRect(13, 13, 97, 57);
painter->setBrush(b);
return;
}
QPen oldPen = painter->pen();
QPen pen = oldPen;
int width = 0;
if (option->state & QStyle::State_Selected)
width += 2;
pen.setWidth(width);
QBrush b = painter->brush();
painter->setBrush(QBrush(fillColor.dark(option->state & QStyle::State_Sunken ? 120 : 100)));
painter->drawRect(QRect(14, 14, 79, 39));
painter->setBrush(b);
if (lod >= 1) {
painter->setPen(QPen(Qt::gray, 1));
painter->drawLine(15, 54, 94, 54);
painter->drawLine(94, 53, 94, 15);
painter->setPen(QPen(Qt::black, 0));
}
// Draw text
if (lod >= 2) {
QFont font("Times", 10);
font.setStyleStrategy(QFont::ForceOutline);
painter->setFont(font);
painter->save();
painter->scale(0.1, 0.1);
painter->drawText(170, 180, QString("Model: VSC-2000 (Very Small Chip) at %1x%2").arg(x).arg(y));
painter->drawText(170, 200, QString("Serial number: DLWR-WEER-123L-ZZ33-SDSJ"));
painter->drawText(170, 220, QString("Manufacturer: Chip Manufacturer"));
painter->restore();
}
// Draw lines
QVarLengthArray<QLineF, 36> lines;
if (lod >= 0.5) {
for (int i = 0; i <= 10; i += (lod > 0.5 ? 1 : 2)) {
lines.append(QLineF(18 + 7 * i, 13, 18 + 7 * i, 5));
lines.append(QLineF(18 + 7 * i, 54, 18 + 7 * i, 62));
}
for (int i = 0; i <= 6; i += (lod > 0.5 ? 1 : 2)) {
lines.append(QLineF(5, 18 + i * 5, 13, 18 + i * 5));
lines.append(QLineF(94, 18 + i * 5, 102, 18 + i * 5));
}
}
if (lod >= 0.4) {
const QLineF lineData[] = {
QLineF(25, 35, 35, 35),
QLineF(35, 30, 35, 40),
QLineF(35, 30, 45, 35),
QLineF(35, 40, 45, 35),
QLineF(45, 30, 45, 40),
QLineF(45, 35, 55, 35)
};
lines.append(lineData, 6);
}
painter->drawLines(lines.data(), lines.size());
// Draw red ink
if (stuff.size() > 1) {
QPen p = painter->pen();
painter->setPen(QPen(Qt::red, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
painter->setBrush(Qt::NoBrush);
QPainterPath path;
path.moveTo(stuff.first());
for (int i = 1; i < stuff.size(); ++i)
path.lineTo(stuff.at(i));
painter->drawPath(path);
painter->setPen(p);
}
}
void Chip::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsItem::mousePressEvent(event);
update();
}
void Chip::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if (event->modifiers() & Qt::ShiftModifier) {
stuff << event->pos();
update();
return;
}
QGraphicsItem::mouseMoveEvent(event);
}
void Chip::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsItem::mouseReleaseEvent(event);
update();
}
QColor Chip::getColor() const
{
return color;
}
int Chip::getX() const
{
return x;
}
int Chip::getY() const
{
return y;
}
void Chip::setColor(const QColor &color)
{
this->color = color;
}
void Chip::setX(const int &x)
{
this->x = x;
}
void Chip::setY(const int &y)
{
this->y = y;
}
chip.h
#ifndef CHIP_H
#define CHIP_H
#include <QtGui/QColor>
#include <QDeclarativeItem>
class Chip : public QDeclarativeItem
{
Q_OBJECT
Q_PROPERTY(int x READ getX WRITE setX)
Q_PROPERTY(int y READ getY WRITE setY)
Q_PROPERTY(QColor color READ getColor WRITE setColor)
public:
Chip(QDeclarativeItem *parent = 0);
Chip(const QColor &color, int x, int y);
QRectF boundingRect() const;
QColor getColor() const;
int getX() const;
int getY() const;
void setColor(const QColor &color);
void setX(const int &x);
void setY(const int &y);
QPainterPath shape() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget);
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
private:
int x, y;
QColor color;
QList<QPointF> stuff;
};
#endif
In my investigation of this issue, i learned that you can add custom widgets to the QT Designer. I might have to check that out as well before I make my decision. Any help will be appreciated, thanks.

UPDATE: Dec/2015
You have to mark it as 'supported'
Documentation clearly states that you have to explicitely mark it as supported, otherwise you will get blank boxes.
The items of an unsupported plugin are not painted in the Qt Quick
Designer, but they are still available as empty boxes and the
properties can be edited.
In order to do this you must build it as a plugin and then include the keyword designersupported into a qmldir file in the same folder your plugin shared object/dll is placed. This is a whitelist and Qt Creator's puppet will trust your code, be sure not to make long operations or crash, or you will crash the puppet and make the designer useless.
Old and outdated answer below
Same thing happens to me. This seems to be a bug in QtCreator. I digged into the code of the Rectangle QML item and found no special instructions. So QtCreator must have it hard coded or something.
See this: http://developer.qt.nokia.com/forums/viewthread/2555

They are blank, custom components created with C++ cant be show, but they work fine when running your app. There is a bug placed into Qt for allowing that, but seems to be low priority now as it requires internal Qt changes.
Update:
Just recently, after some discussion, a task was created to implement a mechanism for shadowing custom components, and it was marked P1, nice!. See this bug report, they have even added some work in progress patch you can test. That's a patch for Qt, so we might (or not) be close to having it inside Qt 5.4 and then Qt Creator will have that support. Remember Qt has a release cycle of 6 months now, so it might not be that far. Please register and vote for it, if you need it.

Related

How to add curve path to connect flow widgets from two columns in qt?

I know this question is somehow hard to describe, so a picture may help, as following:
I'm developing application in qt-5.15.x. Say I have a window or widget or something else which can layout two columns of widgets(customized, call it rectangle here), I want to:
drag and drop one item up or down within same column by mouse
connect two widgets from two different columns with a customized curve path by mouse
all elements(rectangle and curve item) have mouse events: move, hover, click and key event
the contents of window or widget can scroll vertically due to more and more items will be added
Before this, I have implemented bazier curve, graphicsview with customized widgets and connecting these widgets with bazier curve, but all these widgets don't lay on line(horizontally or vertically).
So my question is not about how to implement it in detail, but just a guide - what widget , layout or event something else in qt I can use, or which document I can refer to. I have searched a lot, but with no results.
OPs requirement can be achieved by simply deriving a widget from QWidget and overriding the paintEvent().
Beside of that, the derived widget still can contain children and layout managers, so that both can be combined.
Sample code testQWidgetPaintOverChildren.cc to demonstrate:
#include <QtWidgets>
class Canvas: public QWidget {
private:
using Link = std::pair<int, int>;
std::vector<Link> _links;
public:
void addLink(int from, int to)
{
_links.emplace_back(from, to);
update();
}
protected:
virtual void paintEvent(QPaintEvent *pQEvent) override;
};
void Canvas::paintEvent(QPaintEvent* pQEvent)
{
QWidget::paintEvent(pQEvent);
const int lenTan = 64;
QPainter qPainter(this);
auto drawCurve = [&](const QPoint& qPosFrom, const QPoint& qPosTo) {
QPainterPath qPath;
qPath.moveTo(qPosFrom);
qPath.cubicTo(qPosFrom + QPoint(lenTan, 0), qPosTo - QPoint(lenTan, 0), qPosTo);
qPainter.drawPath(qPath);
};
const QObjectList& pQChildren = children();
for (const Link& link : _links) {
const int from = link.first;
if (from >= pQChildren.size()) continue; // invalid from index
const QWidget* pQWidgetFrom
= dynamic_cast<const QWidget*>(pQChildren[from]);
if (!pQWidgetFrom) continue; // shouldn't happen
const int to = link.second;
if (to >= pQChildren.size()) continue; // invalid to index
const QWidget* pQWidgetTo
= dynamic_cast<const QWidget*>(pQChildren[to]);
if (!pQWidgetTo) continue; // shouldn't happen
const QPoint qPosFrom
= pQWidgetFrom->pos() + QPoint(3 * pQWidgetFrom->width() / 4, pQWidgetFrom->height() / 2);
const QPoint qPosTo
= pQWidgetTo->pos() + QPoint(1 * pQWidgetTo->width() / 4, pQWidgetTo->height() / 2);
//qPainter.drawLine(qPosFrom, qPosTo);
drawCurve(qPosFrom, qPosTo);
}
}
int main(int argc, char** argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
// setup GUI
Canvas qCanvas;
qCanvas.setWindowTitle("Test Draw Over Children");
qCanvas.resize(320, 240);
QGridLayout qGrid;
qGrid.setSpacing(16);
#define ITEM(ROW, COL) \
QLabel qLbl##ROW##COL("txt "#ROW", "#COL); \
qLbl##ROW##COL.setAlignment(Qt::AlignCenter); \
qLbl##ROW##COL.setFrameStyle(QFrame::Box | QFrame::Plain); \
qGrid.addWidget(&qLbl##ROW##COL, ROW - 1, COL - 1)
ITEM(1, 1); ITEM(1, 2);
ITEM(2, 1); ITEM(2, 2);
ITEM(3, 1); ITEM(3, 2);
ITEM(4, 1); ITEM(4, 2);
qCanvas.setLayout(&qGrid);
qCanvas.addLink(1, 8);
qCanvas.addLink(5, 2);
qCanvas.show();
// runtime loop
return app.exec();
}
Output:
Qt Version: 5.15.1
The drawback of this first attempt is that the links are drawn under the children. In the case of the QLabel, this isn't visible as QLabels are mostly transparent. Replacing them by QPushButtons makes this obvious.
This can be solved by using two widgets, one as container for children, the other for drawing the links, and ensuring that the second widget has the same position and size than the first.
Improved sample code testQWidgetPaintOverChildren.cc:
#include <QtWidgets>
class Widget: public QWidget {
private:
using Link = std::pair<int, int>;
struct Canvas: public QWidget {
std::vector<Link> links;
using QWidget::QWidget;
virtual void paintEvent(QPaintEvent *pQEvent) override;
} _canvas;
public:
explicit Widget(QWidget* pQParent = nullptr):
QWidget(pQParent),
_canvas(this)
{ }
public:
void addLink(int from, int to)
{
_canvas.links.emplace_back(from, to);
_canvas.update();
_canvas.setParent(nullptr);
_canvas.setParent(this);
}
protected:
virtual void resizeEvent(QResizeEvent* pQEvent) override
{
QWidget::resizeEvent(pQEvent);
_canvas.resize(size());
}
};
void Widget::Canvas::paintEvent(QPaintEvent* pQEvent)
{
QWidget::paintEvent(pQEvent);
const int lenTan = 64;
QPainter qPainter(this);
auto drawCurve = [&](const QPoint& qPosFrom, const QPoint& qPosTo) {
QPainterPath qPath;
qPath.moveTo(qPosFrom);
qPath.cubicTo(qPosFrom + QPoint(lenTan, 0), qPosTo - QPoint(lenTan, 0), qPosTo);
qPainter.drawPath(qPath);
};
const QObjectList& pQChildren = parent()->children();
for (const Link& link : links) {
const int from = link.first;
if (from >= pQChildren.size()) continue; // invalid from index
const QWidget* pQWidgetFrom
= dynamic_cast<const QWidget*>(pQChildren[from]);
if (!pQWidgetFrom) continue; // shouldn't happen
const int to = link.second;
if (to >= pQChildren.size()) continue; // invalid to index
const QWidget* pQWidgetTo
= dynamic_cast<const QWidget*>(pQChildren[to]);
if (!pQWidgetTo) continue; // shouldn't happen
const QPoint qPosFrom
= pQWidgetFrom->pos() + QPoint(3 * pQWidgetFrom->width() / 4, pQWidgetFrom->height() / 2);
const QPoint qPosTo
= pQWidgetTo->pos() + QPoint(1 * pQWidgetTo->width() / 4, pQWidgetTo->height() / 2);
//qPainter.drawLine(qPosFrom, qPosTo);
drawCurve(qPosFrom, qPosTo);
}
}
int main(int argc, char** argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
// setup GUI
Widget qWinMain;
qWinMain.setWindowTitle("Test Draw Over Children");
qWinMain.resize(320, 240);
QGridLayout qGrid;
qGrid.setSpacing(16);
#define ITEM(ROW, COL) \
QPushButton qBtn##ROW##COL("txt "#ROW", "#COL); \
qGrid.addWidget(&qBtn##ROW##COL, ROW - 1, COL - 1)
ITEM(1, 1); ITEM(1, 2);
ITEM(2, 1); ITEM(2, 2);
ITEM(3, 1); ITEM(3, 2);
ITEM(4, 1); ITEM(4, 2);
#undef ITEM
qWinMain.setLayout(&qGrid);
qWinMain.addLink(1, 8);
qWinMain.addLink(5, 2);
qWinMain.show();
// runtime loop
return app.exec();
}
Output:
Qt Version: 5.15.1

How to connect a QRadioButton of a QTableWidget cell with another QTableWidget cell using an arrow?

I have a QListWidget and a QGraphicsView both subclassed to overwrite some of their members. I prepared a minimal verifiable example showing the problem I have here
From the QListWidget I can drag and drop specific field (represented by a QTableWidget) and drop them into a QGraphicsView and in order to do that I am using a QGraphicsProxyWidget approach as shown below.
The Problem
Now, how do I connect 2 QRadioButton inside cell of a QTableWidget with another cell of another QTableWidget?
It is important to mention that the green QGraphicsRectItem it is used to move around the QTableWidget as well as adjusting its dimension.
Below the result I was able to arrive so far:
And below the expected result I have been trying to achieve:
Below the most important part of the code:
scene.h
#ifndef SCENE_H
#define SCENE_H
#include <QGraphicsScene>
class Scene : public QGraphicsScene
{
public:
Scene(QObject *parent = nullptr);
protected:
void dragEnterEvent(QGraphicsSceneDragDropEvent *event);
void dragMoveEvent(QGraphicsSceneDragDropEvent *event);
void dropEvent(QGraphicsSceneDragDropEvent *event);
};
#endif // SCENE_H
scene.cpp
#include "arrow.h"
#include <QGraphicsSceneDragDropEvent>
#include <QMimeData>
#include <QTableWidget>
#include <QGraphicsProxyWidget>
#include <QVBoxLayout>
#include <QMetaEnum>
#include <QEvent>
#include <QSizeGrip>
#include <QRadioButton>
Scene::Scene(QObject *parent)
{
setBackgroundBrush(Qt::lightGray);
}
void Scene::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
if (event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist"))
event->setAccepted(true);
}
void Scene::dragMoveEvent(QGraphicsSceneDragDropEvent *event) {
if (event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist"))
event->setAccepted(true);
}
void Scene::dropEvent(QGraphicsSceneDragDropEvent *event) {
QByteArray encoded =
event->mimeData()->data("application/x-qabstractitemmodeldatalist");
QDataStream stream(&encoded, QIODevice::ReadOnly);
QStringList rosTables;
QString newString;
while (!stream.atEnd()) {
int row, col;
QMap<int, QVariant> roleDataMap;
stream >> row >> col >> roleDataMap;
rosTables << roleDataMap[Qt::DisplayRole].toString();
}
for (const QString &tableType : rosTables) {
if (tableType == "Images") {
QPoint initPos(0, 0);
auto *wgt = new CustomTableWidget;
auto *proxyControl = addRect(0, 0, 0, 0, QPen(Qt::black),
QBrush(Qt::darkGreen));
auto *sizeGrip = new QSizeGrip(wgt);
auto *layout = new QHBoxLayout(wgt);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(sizeGrip, 0, Qt::AlignRight | Qt::AlignBottom);
connect(wgt, &CustomTableWidget::sizeChanged, [wgt, proxyControl](){
proxyControl->setRect(wgt->geometry().adjusted(-10, -10, 10, 10));
});
wgt->setColumnCount(4);
wgt->setRowCount(4);
for (int ridx = 0; ridx < wgt->rowCount(); ridx++) {
for (int cidx = 0; cidx < wgt->columnCount(); cidx++) {
QRadioButton *radio1, *radio2;
auto* item = new QTableWidgetItem();
item->setText(QString("%1").arg(ridx));
wgt->setItem(ridx,cidx,item);
radio1 = new QRadioButton;
radio2 = new QRadioButton;
wgt->setCellWidget(cidx, 0, radio1);
wgt->setCellWidget(cidx, 3, radio2);
Arrow *arrow = new Arrow;
}
}
auto *const proxy = addWidget(wgt);
proxy->setPos(initPos.x(), initPos.y()
+ proxyControl->rect().height());
proxy->setParentItem(proxyControl);
proxyControl->setPos(initPos.x(), initPos.y());
proxyControl->setFlag(QGraphicsItem::ItemIsMovable, true);
proxyControl->setFlag(QGraphicsItem::ItemIsSelectable, true);
proxyControl->setRect(wgt->geometry().adjusted(-10, -10, 10, 10));
}
}
}
diagramitem.h
#ifndef DIAGRAMITEM_H
#define DIAGRAMITEM_H
#include <QGraphicsPolygonItem>
class Arrow;
class DiagramItem : public QGraphicsPolygonItem
{
public:
DiagramItem(QMenu *contextMenu, QGraphicsItem *parent = Q_NULLPTR);
void removeArrow(Arrow *arrow);
void removeArrows();
void addArrow(Arrow *arrow);
QPixmap image() const;
protected:
void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override;
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
private:
QPolygonF myPolygon;
QList<Arrow*> arrows;
QMenu *myContextMenu;
};
#endif // DIAGRAMITEM_H
diagramitem.cpp
#include "diagramitem.h"
#include "arrow.h"
#include <QPainter>
#include <QGraphicsScene>
#include <QGraphicsSceneContextMenuEvent>
#include <QMenu>
DiagramItem::DiagramItem(QMenu *contextMenu, QGraphicsItem *parent) : QGraphicsPolygonItem(parent)
{
myContextMenu = contextMenu;
setPolygon(myPolygon);
setFlag(QGraphicsItem::ItemIsMovable, true);
setFlag(QGraphicsItem::ItemIsSelectable, true);
setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
}
void DiagramItem::removeArrow(Arrow *arrow)
{
int index = arrows.indexOf(arrow);
if (index != -1)
arrows.removeAt(index);
}
void DiagramItem::removeArrows()
{
foreach (Arrow *arrow, arrows) {
arrow->startItem()->removeArrow(arrow);
arrow->endItem()->removeArrow(arrow);
scene()->removeItem(arrow);
delete arrow;
}
}
void DiagramItem::addArrow(Arrow *arrow)
{
arrows.append(arrow);
}
void DiagramItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
scene()->clearSelection();
setSelected(true);
myContextMenu->exec(event->screenPos());
}
QVariant DiagramItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
if (change == QGraphicsItem::ItemPositionChange) {
foreach (Arrow *arrow, arrows) {
arrow->updatePosition();
}
}
return value;
}
arrow.h
#ifndef ARROW_H
#define ARROW_H
#include <QGraphicsLineItem>
#include "diagramitem.h"
class Arrow : public QGraphicsLineItem
{
public:
enum { Type = UserType + 4 };
Arrow(DiagramItem *startItem, DiagramItem *endItem,
QGraphicsItem *parent = nullptr);
DiagramItem *startItem() const { return myStartItem; }
DiagramItem *endItem() const { return myEndItem; }
QPainterPath shape() const override;
void setColor(const QColor &color) {
myColor = color;
}
int type() const override { return Type; }
void updatePosition();
protected:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override;
private:
QColor myColor;
DiagramItem *myStartItem;
DiagramItem *myEndItem;
QPolygonF arrowHead;
};
#endif // ARROW_H
arrow.cpp
#include "arrow.h"
#include <QPen>
#include <QPainter>
#include "qmath.h"
Arrow::Arrow(DiagramItem *startItem, DiagramItem *endItem, QGraphicsItem *parent) : QGraphicsLineItem(parent)
{
myStartItem = startItem;
myEndItem = endItem;
myColor = Qt::GlobalColor::black;
setPen(QPen(myColor, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
setFlag(QGraphicsItem::ItemIsSelectable, true);
}
QPainterPath Arrow::shape() const
{
QPainterPath path = QGraphicsLineItem::shape();
path.addPolygon(arrowHead);
return path;
}
void Arrow::updatePosition()
{
QLineF line(mapFromItem(myStartItem, 0, 0), mapFromItem(myEndItem, 0, 0));
setLine(line);
}
void Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option)
Q_UNUSED(widget)
if (myStartItem->collidesWithItem(myEndItem))
return;
QPen myPen = pen();
myPen.setColor(myColor);
qreal arrowSize = 20;
painter->setPen(myPen);
painter->setBrush(myColor);
QLineF centerLine(myStartItem->pos(), myEndItem->pos());
QPolygonF endPolygon = myEndItem->polygon();
QPointF p1 = endPolygon.first() + myEndItem->pos();
QPointF p2;
QPointF intersectPoint;
QLineF polyLine;
for (int i = 1; i < endPolygon.count(); ++i) {
p2 = endPolygon.at(i) + myEndItem->pos();
polyLine = QLineF(p1, p2);
QLineF::IntersectType intersectType =
polyLine.intersect(centerLine, &intersectPoint);
if (intersectType == QLineF::BoundedIntersection)
break;
p1 = p2;
}
setLine(QLineF(intersectPoint, myStartItem->pos()));
double angle = std::atan2(-line().dy(), line().dx());
QPointF arrowP1 = line().p1() + QPointF(sin(angle + M_PI / 3) * arrowSize,
cos(angle + M_PI / 3) * arrowSize);
QPointF arrowP2 = line().p1() + QPointF(sin(angle + M_PI - M_PI / 3) * arrowSize,
cos(angle + M_PI - M_PI / 3) * arrowSize);
arrowHead.clear();
arrowHead << line().p1() << arrowP1 << arrowP2;
painter->drawLine(line());
painter->drawPolygon(arrowHead);
if (isSelected()) {
painter->setPen(QPen(myColor, 1, Qt::DashLine));
QLineF myLine = line();
myLine.translate(0, 4.0);
painter->drawLine(myLine);
myLine.translate(0,-8.0);
painter->drawLine(myLine);
}
}
What I have done so far to solve the problem:
1) I came across this post which was useful to understand the initial idea on how to do that, but it didn't really provide a way, or an implementation idea on how to best proceed
2) I researched the official documentation and before asking this question I went through the whole Diagram Scene example provided and understood how to create an Arrow object. The documentation about that was very good and made me understand how the graphics line item has to be formed.
However I was not able (coming back to my example) how to make "aware" the QRadioButton that I am trying to use its center as starting point for an arrow ad, therefore, how do I make "aware" the destination QRadioButton in another cell that it has to be connected there?
Below a particular of what I mean:
So basically the start point of the QRadioButton change color (or style) and the arrival point also change color.
3) I thought that the Arrow object has to be created inside the subclassed QGraphicsScene since it already handles the mouse events.
4) Despite what I tried so far I could not find any other useful help. Although I am still investigating how to do that.
If anyone has ever been in the same situation please provide guidance on how to better proceed to solve this problem and find a solution to this issue.
Solution
When a start and end radio buttons are checked, you need to create the arrow with those buttons as start and end nodes, e.g.:
void Backend::onInputRadioButton(bool checked)
{
m_endNode = checked ? static_cast<QRadioButton *>(sender()) : nullptr;
if (m_startNode && m_endNode)
m_scene->addItem(new ArrowItem(m_startNode, m_endNode));
}
Then you need to connect the signal of the top-most graphics items, which hold the tables, with the updatePosition slot of the ArrowItem, e.g.:
connect(m_startItem->property("item").value<MovableItem *>(),
&MovableItem::itemMoved, this, &ArrowItem::updatePosition);
connect(m_endItem->property("item").value<MovableItem *>(),
&MovableItem::itemMoved, this, &ArrowItem::updatePosition);
Note: I am using a property to hold a reference to the container item.
Finally, you need to update the arrow line, e.g.:
void ArrowItem::updatePosition()
{
QPointF offset(7, 15);
QPointF p1 = m_startItem->property("item").value<MovableItem *>()->pos()
+ m_startItem->parentWidget()->mapToParent(m_startItem->pos())
+ offset;
QPointF p2 = m_endItem->property("item").value<MovableItem *>()->pos()
+ m_endItem->parentWidget()->mapToParent(m_endItem->pos())
+ offset;
setLine(QLineF(p1, p2));
}
Example
I have dared to suggest improvements in your code. You can find the complete example I wrote for you on GitHub.
Result
The provided example produces the following result:
Note: The arrow heads are missing. Check once again the Diagram Scene Example to get an idea of how to draw them.

How to use qss on a custom widget plugin

I followed the guide of the Qt documentation and completed a custom widget plugin. And now it can run successfully in QtDesigner.
This is the example I refer to:
https://doc.qt.io/qt-5/designer-creating-custom-widgets.html
This is a clock widget with three hands.
I want to change the color of the hands through qss, just like this:
Clock {
hour-hand: #333333;
minute-hand: #f7f7f7;
second-hand: #cccccc;
}
I read the document about QStyle, the document about QStyleOption, and the document about QStylePlugin. But I haven't figured out the relationship between them well, and I don't know what Class should be used to solve my problem.
Qt StyleSheet is dedicated to painting predefined widgets since its implementation is a QStyle of Qt's private API, therefore new properties cannot be predefined. But within the Qt StyleSheet properties there is a qproperty-foo that can be used in this case, for example to set the color of the hour hand, and for this you must create a QProperty:
analogclock.h
#ifndef ANALOGCLOCK_H
#define ANALOGCLOCK_H
#include <QWidget>
#include <QtUiPlugin/QDesignerExportWidget>
class QDESIGNER_WIDGET_EXPORT AnalogClock : public QWidget
{
Q_OBJECT
Q_PROPERTY(QColor hourColor READ hourColor WRITE setHourColor)
public:
explicit AnalogClock(QWidget *parent = nullptr);
QColor hourColor() const;
void setHourColor(QColor hourColor);
protected:
void paintEvent(QPaintEvent *event) override;
private:
QColor m_hourColor;
};
#endif
analogclock.cpp
#include "analogclock.h"
#include <QMouseEvent>
#include <QPainter>
#include <QTime>
#include <QTimer>
AnalogClock::AnalogClock(QWidget *parent)
: QWidget(parent), m_hourColor(QColor(127, 0, 127))
{
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, QOverload::of(&QWidget::update));
timer->start(1000);
setWindowTitle(tr("Analog Clock"));
resize(200, 200);
}
QColor AnalogClock::hourColor() const
{
return m_hourColor;
}
void AnalogClock::setHourColor(QColor hourColor)
{
if (m_hourColor == hourColor)
return;
m_hourColor = hourColor;
update();
}
void AnalogClock::paintEvent(QPaintEvent *)
{
static const QPoint hourHand[3] = {
QPoint(7, 8),
QPoint(-7, 8),
QPoint(0, -40)
};
static const QPoint minuteHand[3] = {
QPoint(7, 8),
QPoint(-7, 8),
QPoint(0, -70)
};
QColor minuteColor(0, 127, 127, 191);
int side = qMin(width(), height());
QTime time = QTime::currentTime();
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.translate(width() / 2, height() / 2);
painter.scale(side / 200.0, side / 200.0);
painter.setPen(Qt::NoPen);
painter.setBrush(m_hourColor);
painter.save();
painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)));
painter.drawConvexPolygon(hourHand, 3);
painter.restore();
painter.setPen(m_hourColor);
for (int i = 0; i < 12; ++i) {
painter.drawLine(88, 0, 96, 0);
painter.rotate(30.0);
}
painter.setPen(Qt::NoPen);
painter.setBrush(minuteColor);
painter.save();
painter.rotate(6.0 * (time.minute() + time.second() / 60.0));
painter.drawConvexPolygon(minuteHand, 3);
painter.restore();
painter.setPen(minuteColor);
for (int j = 0; j < 60; ++j) {
if ((j % 5) != 0)
painter.drawLine(92, 0, 96, 0);
painter.rotate(6.0);
}
}
and then you can use:
AnalogClock {
qproperty-hourColor: #333333;
}
Note: By default the QProperty have the DESIGNABLE in true so you can also modify the hourColor property from the Property editor:

Drawing by Windows GDI inside of Qt

I am trying to use Windows GDI inside of QGraphicsView paintEvent but have noticed some drawing issues, for example the drawing disappear or blinking when I resize window or minimize and maximize. When I use Qt instead of GDI its working perfectly. Here is the code:
[UPDATED CODE]
#include "CustomView.h"
#include <QPainter>
#include <QPaintEngine>
#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>
using namespace Gdiplus;
#pragma comment (lib,"Gdiplus.lib")
CustomView::CustomView(QWidget *parent)
: QGraphicsView(parent)
{
setAutoFillBackground(true);
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
setAttribute(Qt::WA_NativeWindow, true);
}
CustomView::~CustomView()
{
}
void CustomView::paintEvent(QPaintEvent * event)
{
QPainter painter(viewport());
painter.beginNativePainting();
// Drawing by Windows GDI
HWND hwnd = (HWND)viewport()->winId();
HDC hdc = GetDC(hwnd);
QString text("Test GDI Paint");
RECT rect;
GetClientRect(hwnd, &rect);
HBRUSH hbrRed = CreateSolidBrush(RGB(0, 255, 0));
FillRect(hdc, &rect, hbrRed);
Ellipse(hdc, 50, 50, rect.right - 100, rect.bottom - 100);
SetTextAlign(hdc, TA_CENTER | TA_BASELINE);
TextOutW(hdc, width() / 2, height() / 2, (LPCWSTR)text.utf16(), text.size());
ReleaseDC(hwnd, hdc);
painter.endNativePainting();
QGraphicsView::paintEvent(event);
// Drawing the same by Qt
// QPainter painter(viewport());
// painter.save() ;
// QBrush GreenBrush(Qt::green);
// QBrush WhiteBrush(Qt::white);
// QRect ViewportRect = viewport()->rect();
// painter.fillRect(ViewportRect, GreenBrush);
// painter.drawEllipse(50, 50, ViewportRect.right() - 100, ViewportRect.bottom() - 100);
// QPainterPath EllipsePath;
// EllipsePath.addEllipse(50, 50, ViewportRect.right() - 100, ViewportRect.bottom() - 100);
// painter.fillPath(EllipsePath, WhiteBrush);
// painter.drawText(ViewportRect.width() / 2, ViewportRect.height() / 2, "Test Qt Paint");
// painter.restore();
}
and here is the whole project(Visual Studio 2010 + Qt 5.4.1)[UPDATED ARCHIVE]
https://dl.dropboxusercontent.com/u/105132532/Stackoverflow/Qt5TestApplication.7z
Any ideas?
Solution(edited the code after Kuba Ober's answer)
#include "CustomView.h"
#include <QPainter>
#include <QPaintEngine>
#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>
using namespace Gdiplus;
#pragma comment (lib,"Gdiplus.lib")
CustomView::CustomView(QWidget *parent)
: QGraphicsView(parent)
{
// This brings the original paint engine alive.
QGraphicsView::paintEngine();
setAttribute(Qt::WA_NativeWindow);
setAttribute(Qt::WA_PaintOnScreen);
setRenderHint(QPainter::Antialiasing);
}
CustomView::~CustomView()
{
}
QPaintEngine* CustomView::paintEngine() const
{
return NULL;
}
bool CustomView::event(QEvent * event) {
if (event->type() == QEvent::Paint)
{
bool result = QGraphicsView::event(event);
drawGDI();
return result;
}
else if (event->type() == QEvent::UpdateRequest)
{
bool result = QGraphicsView::event(event);
drawGDI();
return result;
}
return QGraphicsView::event(event);
}
void CustomView::drawGDI()
{
// Drawing by Windows GDI
HWND hwnd = (HWND)viewport()->winId();
HDC hdc = GetDC(hwnd);
QString text("Test GDI Paint");
RECT rect;
GetClientRect(hwnd, &rect);
HBRUSH hbrRed = CreateSolidBrush(RGB(0, 255, 0));
FillRect(hdc, &rect, hbrRed);
Ellipse(hdc, 50, 50, rect.right - 100, rect.bottom - 100);
SetTextAlign(hdc, TA_CENTER | TA_BASELINE);
TextOutW(hdc, width() / 2, height() / 2, (LPCWSTR)text.utf16(), text.size());
ReleaseDC(hwnd, hdc);
}
A QWidget that intends to paint via GDI only must:
Reimplement paintEngine to return nullptr.
Set the WA_PaintOnScreen attribute.
Optionally set the WA_NativeWindow attribute. This only speeds up the first redraw of the widget.
Reimplement QObject::event and catch Paint and UpdateRequest events. These events should result in calling a method that does the GDI painting. The events must not be forwarded to the base class.
Additionally, a QWidget that paints via GDI on top of contents painted through paintEvent/QPainter, must additionally:
Call base class's paintEngine() method once in the constructor. This will instantiate the native paint engine for the widget.
In the QObject::event implementation, the base class's event must be called before doing the GDI painting. This will draw the contents using the raster paint engine, and return control to you to overdraw some other contents on top of it.
The example below shows how to overpaint on top of the drawing done by Qt's paint system. Of course, since the painting is done on top contents already drawn by Qt, there's flicker.
Doing GDI painting on top of the Qt's backing store, avoiding the flicker, is also possible, but requires a somewhat different approach.
#include <QApplication>
#include <QGraphicsObject>
#include <QPropertyAnimation>
#include <QGraphicsView>
#include <QPainter>
#include <QPaintEvent>
#include <windows.h>
class View : public QGraphicsView {
public:
View(QWidget *parent = 0) : QGraphicsView(parent)
{
// This brings the original paint engine alive.
QGraphicsView::paintEngine();
//setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
setAttribute(Qt::WA_NativeWindow);
setAttribute(Qt::WA_PaintOnScreen);
setRenderHint(QPainter::Antialiasing);
}
QPaintEngine * paintEngine() const Q_DECL_OVERRIDE { return 0; }
bool event(QEvent * event) Q_DECL_OVERRIDE {
if (event->type() == QEvent::Paint) {
bool result = QGraphicsView::event(event);
paintOverlay();
return result;
}
if (event->type() == QEvent::UpdateRequest) {
bool result = QGraphicsView::event(event);
paintOverlay();
return result;
}
return QGraphicsView::event(event);
}
void resizeEvent(QResizeEvent *) {
fitInView(-2, -2, 4, 4, Qt::KeepAspectRatio);
}
virtual void paintOverlay();
};
void View::paintOverlay()
{
// We're called after the native painter has done its thing
HWND hwnd = (HWND)viewport()->winId();
HDC hdc = GetDC(hwnd);
HBRUSH hbrGreen = CreateHatchBrush(HS_BDIAGONAL, RGB(0, 255, 0));
RECT rect;
GetClientRect(hwnd, &rect);
SetBkMode(hdc, TRANSPARENT);
SelectObject(hdc, hbrGreen);
Rectangle(hdc, 0, 0, rect.right, rect.bottom);
SelectObject(hdc, GetStockObject(NULL_BRUSH));
Ellipse(hdc, 50, 50, rect.right - 100, rect.bottom - 100);
QString text("Test GDI Paint");
SetTextAlign(hdc, TA_CENTER | TA_BASELINE);
TextOutW(hdc, width() / 2, height() / 2, (LPCWSTR)text.utf16(), text.size());
DeleteObject(hbrGreen);
ReleaseDC(hwnd, hdc);
}
class EmptyGraphicsObject : public QGraphicsObject
{
public:
EmptyGraphicsObject() {}
QRectF boundingRect() const { return QRectF(0, 0, 0, 0); }
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {}
};
void setupScene(QGraphicsScene &s)
{
QGraphicsObject * obj = new EmptyGraphicsObject;
QGraphicsRectItem * rect = new QGraphicsRectItem(-1, 0.3, 2, 0.3, obj);
QPropertyAnimation * anim = new QPropertyAnimation(obj, "rotation", &s);
s.addItem(obj);
rect->setPen(QPen(Qt::darkBlue, 0.1));
anim->setDuration(2000);
anim->setStartValue(0);
anim->setEndValue(360);
anim->setEasingCurve(QEasingCurve::InBounce);
anim->setLoopCount(-1);
anim->start();
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene s;
setupScene(s);
View view;
view.setScene(&s);
view.show();
return a.exec();
}

How to extend QML Rectangle in C++

When I want to create a new Qt Quick Item in C++ in I extend QQuickItem. It happens that I want my new item to have the same basic properties of a Rectangle. Is there any class I can extend to have a Rectangle directly?
Rectangle is actually QQuickRectangle, but it is not exported to be used in C++. The header file is QtQuick\private\qquickrectangle_p.h.
Check my version of an AdvancedRectangle that can have a different radius for each corner. I had to re-implement Rectangle's behavior.
advancedrectangle.h
#ifndef ADVANCEDRECTANGLE_H
#define ADVANCEDRECTANGLE_H
#include <QQuickPaintedItem>
#include <QPainter>
#include <QPen>
class AdvancedRectangle : public QQuickPaintedItem
{
Q_OBJECT
public:
explicit AdvancedRectangle(QQuickItem *parent = 0);
Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
QColor color() const;
void setColor(QColor color);
Q_PROPERTY(qreal radius READ radius WRITE setRadius NOTIFY radiusChanged)
qreal radius() const;
void setRadius(qreal r);
Q_PROPERTY(qreal radiusTopLeft READ radiusTopLeft WRITE setRadiusTopLeft NOTIFY radiusTopLeftChanged)
qreal radiusTopLeft() const;
void setRadiusTopLeft(qreal r);
Q_PROPERTY(qreal radiusTopRight READ radiusTopRight WRITE setRadiusTopRight NOTIFY radiusTopRightChanged)
qreal radiusTopRight() const;
void setRadiusTopRight(qreal r);
Q_PROPERTY(qreal radiusBottomRight READ radiusBottomRight WRITE setRadiusBottomRight NOTIFY radiusBottomRightChanged)
qreal radiusBottomRight() const;
void setRadiusBottomRight(qreal r);
Q_PROPERTY(qreal radiusBottomLeft READ radiusBottomLeft WRITE setRadiusBottomLeft NOTIFY radiusBottomLeftChanged)
qreal radiusBottomLeft() const;
void setRadiusBottomLeft(qreal r);
void paint(QPainter *painter);
enum START_ANGELS {
START_E = 0,
START_N = 90,
START_W = 180,
START_S = 270
};
signals:
void colorChanged();
void radiusChanged();
void radiusTopLeftChanged();
void radiusTopRightChanged();
void radiusBottomRightChanged();
void radiusBottomLeftChanged();
public slots:
private:
QColor color_ = QColor(255, 255, 255);
qreal radius_ = 0.0;
qreal radiusTopLeft_ = -1;
qreal radiusTopRight_ = -1;
qreal radiusBottomRight_ = -1;
qreal radiusBottomLeft_ = -1;
private slots:
void onAppearanceChanged();
};
#endif // ADVANCEDRECTANGLE_H
advancedrectangle.cpp
#include "advancedrectangle.h"
AdvancedRectangle::AdvancedRectangle(QQuickItem *parent) :
QQuickPaintedItem(parent)
{
connect(this, SIGNAL(widthChanged()), SLOT(onAppearanceChanged()));
connect(this, SIGNAL(heightChanged()), SLOT(onAppearanceChanged()));
connect(this, SIGNAL(colorChanged()), SLOT(onAppearanceChanged()));
}
QColor AdvancedRectangle::color() const
{
return color_;
}
void AdvancedRectangle::setColor(QColor color)
{
if (color_ == color) return;
color_ = color;
emit colorChanged();
}
qreal AdvancedRectangle::radius() const
{
return radius_;
}
void AdvancedRectangle::setRadius(qreal r)
{
if (r == radius_) return;
radius_ = r;
emit radiusChanged();
}
qreal AdvancedRectangle::radiusTopLeft() const
{
if (radiusTopLeft_ >= 0) return radiusTopLeft_;
else return radius_;
}
void AdvancedRectangle::setRadiusTopLeft(qreal r)
{
if (r == radiusTopLeft_) return;
radiusTopLeft_ = r;
emit radiusTopLeftChanged();
}
qreal AdvancedRectangle::radiusTopRight() const
{
if (radiusTopRight_ >= 0) return radiusTopRight_;
else return radius_;
}
void AdvancedRectangle::setRadiusTopRight(qreal r)
{
if (r == radiusTopRight_) return;
radiusTopRight_ = r;
emit radiusTopRightChanged();
}
qreal AdvancedRectangle::radiusBottomRight() const
{
if (radiusBottomRight_ >= 0) return radiusBottomRight_;
else return radius_;
}
void AdvancedRectangle::setRadiusBottomRight(qreal r)
{
if (r == radiusBottomRight_) return;
radiusBottomRight_ = r;
emit radiusBottomRightChanged();
}
qreal AdvancedRectangle::radiusBottomLeft() const
{
if (radiusBottomLeft_ >= 0) return radiusBottomLeft_;
else return radius_;
}
void AdvancedRectangle::setRadiusBottomLeft(qreal r)
{
if (r == radiusBottomLeft_) return;
radiusBottomLeft_ = r;
emit radiusBottomLeftChanged();
}
void AdvancedRectangle::paint(QPainter *painter)
{
QPen pen(Qt::NoPen);
painter->setPen(pen);
QBrush brush(color_);
painter->setBrush(brush);
painter->setRenderHints(QPainter::Antialiasing, true);
int _width = width();
int _height = height();
QRectF rectangle;
// top-left
rectangle = QRectF(0, 0, 2*radiusTopLeft(), 2*radiusTopLeft());
painter->drawPie(rectangle, START_W * 16, 90 * -1 * 16);
// top-right
rectangle = QRectF(_width-2*radiusTopRight(), 0, 2*radiusTopRight(), 2*radiusTopRight());
painter->drawPie(rectangle, START_N * 16, 90 * -1 * 16);
// bottom-right
rectangle = QRectF(_width-2*radiusBottomRight(), _height-2*radiusBottomRight(), 2*radiusBottomRight(), 2*radiusBottomRight());
painter->drawPie(rectangle, START_E * 16, 90 * -1 * 16);
// bottom-left
rectangle = QRectF(0, _height-2*radiusBottomLeft(), 2*radiusBottomLeft(), 2*radiusBottomLeft());
painter->drawPie(rectangle, START_S * 16, 90 * -1 * 16);
QPointF points[12] = {
QPointF(radiusTopLeft(), 0),
QPointF(radiusTopLeft(), radiusTopLeft()),
QPointF(0, radiusTopLeft()),
QPointF(0, _height-radiusBottomLeft()),
QPointF(radiusBottomLeft(), _height-radiusBottomLeft()),
QPointF(radiusBottomLeft(), _height),
QPointF(_width-radiusBottomRight(), _height),
QPointF(_width-radiusBottomRight(), _height-radiusBottomRight()),
QPointF(_width, _height-radiusBottomRight()),
QPointF(_width, radiusTopRight()),
QPointF(_width-radiusTopRight(), radiusTopRight()),
QPointF(_width-radiusTopRight(), 0)
};
painter->drawPolygon(points, 12);
}
void AdvancedRectangle::onAppearanceChanged()
{
int new_width = width();
int new_height = height();
update(QRect(0, 0, new_width, new_height));
}
Let me know if you need that MIT licensed.

Resources