Search code examples
qthovercursorqwidget

Show a square Cursor


How could I show a square instead of a cursor in QT for eraser in drawing app?

In other words how could I have a square with a side of a specific length instead of a cursor when I am hovering over the QWidget?


Solution

  • You have to create a QPixmap that draws the rectangle creating a QCursor and then set it to the widget you want.

    #include <QApplication>
    #include <QGraphicsView>
    #include <QHBoxLayout>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        QPixmap pixmap(QSize(64, 64));
        pixmap.fill(Qt::transparent);
    
        QPainter painter(&pixmap);
        QRect r(QPoint(), pixmap.size());
        r.adjust(1, 1, -1, -1);
        painter.drawRect(r);
        painter.end();
    
        QCursor cursor(pixmap);
    
        QWidget w;
        QHBoxLayout lay(&w);
    
        QGraphicsView view1;
        view1.setCursor(cursor);
    
        QGraphicsView view2;
    
        lay.addWidget(&view1);
        lay.addWidget(&view2);
        w.show();
    
        return a.exec();
    }