Search code examples
qtqwidget

make Custom QWidget selectable


I'm working on a boardgame and I'm trying to make QWidgets (Rectangles) selectable. So I have a BoardView (inherited from QWidget) which contains BuildingViews, PlantationViews (both inherited from QWidget). It all shows up on the window, but it is not clickable. How can I make this clickable?


Solution

  • You could try to make a QMouseEvent implementation where the widget ID is forwarded, something like this:

    In the implementation of your widget (e.g. YourWidget.cpp):

    YourWidget::MouseReleaseEvent(QMouseEvent *event)
    {
         emit clickedWithMouse(this);    // this is a signal, declared in YourWidget.h
    }
    

    In the "main" game file (e.g. Game.cpp):

    Game::onButtonClicked(YourWidget* widget)    // this is a public slot, you must connect all YourWidgets's clickedWithMouse signals to this slot (in Game object code, e.g. when initialising the board)
    {
        lastWidget = widget; //save the widget "ID" (lastWidget is a member of class Game)
        someFunction(widget); //do something with the widget (if you wish)
    }