#include <QtWidgets>class MyItem : public QGraphicsObject{public: MyItem(int pinCount, QColor color, QSizeF size, QGraphicsItem* parent = nullptr) : QGraphicsObject(parent) , m_pinCount(pinCount) , m_color(color) , m_size(size) {} QRectF boundingRect() const override { return QRectF(QPointF(0, 0), m_size); } QPainterPath shape() const override { QPainterPath path; path.addRect(QRectF(QPointF(0, 0), m_size)); return path; } void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override { Q_UNUSED(option) Q_UNUSED(widget) painter->setPen(Qt::NoPen); painter->setBrush(m_color); painter->drawRect(boundingRect()); painter->setPen(Qt::black); painter->setFont(QFont("Arial", 10)); painter->drawText(boundingRect(), Qt::AlignCenter, QString("%1 pins").arg(m_pinCount)); } void mousePressEvent(QGraphicsSceneMouseEvent* event) override { if (event->button() == Qt::LeftButton) { setCursor(Qt::ClosedHandCursor); m_lastPos = event->scenePos(); } } void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override { if (QLineF(event->screenPos(), m_lastPos).length() < QApplication::startDragDistance()) return; QGraphicsObject::mouseMoveEvent(event); setPos(pos() + event->scenePos() - m_lastPos); m_lastPos = event->scenePos(); } void mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override { if (event->button() == Qt::LeftButton) { setCursor(Qt::ArrowCursor); } }private: int m_pinCount; QColor m_color; QSizeF m_size; QPointF m_lastPos;};int main(int argc, char* argv[]){ QApplication app(argc, argv); QGraphicsScene scene; scene.setSceneRect(0, 0, 800, 600); MyItem* item1 = new MyItem(8, Qt::red, QSizeF(80, 60)); item1->setPos(100, 100); scene.addItem(item1); MyItem* item2 = new MyItem(16, Qt::green, QSizeF(120, 80)); item2->setPos(300, 200); scene.addItem(item2); QGraphicsView view(&scene); view.setRenderHint(QPainter::Antialiasing); view.setDragMode(QGraphicsView::RubberBandDrag); view.setViewportUpdateMode(QGraphicsView::FullViewportUpdate); view.show(); return app.exec();}在这个代码中,如何使用TextOut去给矩形框中添加文本
时间: 2023-06-20 16:09:16 浏览: 203
QT小游戏编程2
3星 · 编辑精心推荐
这个代码是使用Qt的绘图框架来实现的,所以不能直接使用TextOut函数。可以在MyItem类的paint函数中使用QPainter的函数来绘制文本,如下所示:
```
void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override
{
Q_UNUSED(option)
Q_UNUSED(widget)
painter->setPen(Qt::NoPen);
painter->setBrush(m_color);
painter->drawRect(boundingRect());
painter->setPen(Qt::black);
painter->setFont(QFont("Arial", 10));
painter->drawText(boundingRect(), Qt::AlignCenter, QString("%1 pins").arg(m_pinCount));
}
```
这段代码中,我们使用了QPainter的setFont函数来设置字体,使用drawText函数来绘制文本。其中,boundingRect()函数返回了该图形项的边界矩形,Qt::AlignCenter表示文本将会居中对齐。这样,每个矩形框中就会显示相应的文本。
阅读全文