Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
custom gfx text item
cmake_minimum_required(VERSION 3.10)
project(examples LANGUAGES CXX)
set(CMAKE_CXX_STANDART 14)
set(CMAKE_CXX_STANDART_REQUIRED ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
find_package(Qt5 COMPONENTS Widgets REQUIRED)
add_executable(gfxext WIN32)
target_sources(gfxext
PRIVATE
gfx_main.cxx
gfxtextitem.cxx gfxtextitem.hxx
)
target_link_libraries(gfxext PRIVATE Qt5::Widgets)
#include <QtWidgets>
#include "gfxtextitem.hxx"
void build_ui(QWidget& view)
{
auto box = new QVBoxLayout;
auto gc = new QGraphicsScene{&view};
auto gfx = new QGraphicsView{gc};
auto txt = new QPlainTextEdit{};
auto btn = new QPushButton("Add text");
gfx->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding);
txt->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
QObject::connect(btn, &QPushButton::clicked, [gc, txt](){
auto item = new GfxTextItem;
item->text = txt->toPlainText();
bool ok;
auto font = QFontDialog::getFont(&ok);
if (ok) {
item->font = font;
}
gc->addItem(item);
});
box->addWidget(gfx);
box->addWidget(txt);
box->addWidget(btn);
view.setLayout(box);
view.resize(600, 600);
}
int main(int argc, char** argv)
{
QApplication app{argc, argv};
QWidget view;
build_ui(view);
view.show();
return app.exec();
}
#include "gfxtextitem.hxx"
GfxTextItem::GfxTextItem(QGraphicsItem* parent)
: QGraphicsItem(parent)
{
auto half = size / 2.0;
rect.setRect(-half, -half, size, size);
font.setFamily("Monospace");
font.setPointSize(10);
setFlag(ItemIsMovable, true);
}
GfxTextItem::~GfxTextItem() = default;
QRectF GfxTextItem::boundingRect() const
{
return rect;
}
QPainterPath GfxTextItem::shape() const
{
QPainterPath p;
p.addRect(rect);
return p;
}
void GfxTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/)
{
painter->save();
painter->setRenderHint(QPainter::Antialiasing, true);
painter->setRenderHint(QPainter::TextAntialiasing, true);
painter->setFont(font);
painter->drawRect(rect);
painter->drawText(rect, Qt::AlignCenter | Qt::TextSingleLine, text);
painter->restore();
}
#pragma once
#include <QGraphicsItem>
#include <QtCore>
#include <QtGui>
class GfxTextItem: public QGraphicsItem
{
public:
explicit GfxTextItem(QGraphicsItem* parent = nullptr);
~GfxTextItem() override;
// QGraphicsItem interface
public:
QRectF boundingRect() const override;
QPainterPath shape() const override;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
QRectF rect;
QFont font;
QString text;
double size = 100.0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment