Search code examples
c++qtqgridlayout

QT Gridlayout Item not highlight after clicking?


I have a grid layout as(vtkOpenGLWidget) and inside I distribute the layout in four section. So, I want to highlight the view port when i will clicking on the it. This is my grid layout image view :

enter image description here

I will use this code for highlighting the view port code:

void QvtkOpenGLWidgetdrag::paintEvent(QPaintEvent *event)
{
    QOpenGLWidget::paintEvent(event);

    QPainter painter(this);

    painter.setPen(QPen(QBrush(Qt::blue), 2));

    if (hasFocus())
        painter.drawRect(QRect(1, 1, width() - 2, height() - 2));
}

Its work fine, when i will clicked on the viewport. But i am getting issue when i will select any other module inside the Ui-viewer then it wil by default shows unselected. But, I have selected everytime and once i will select to the other viewport then only it unselect and select to the next view port and vice versa.

Any help is considerable for me. Thank you in advance


Solution

  • Note: Your question is not very clear, so I will try to guess the right solution for you.

    Cause

    The focus policy of QOpenGLWidget is set to Qt::NoFocus by default. Furthermore, this widget does not respect the stylesheet.

    Solution

    Subclass QOpenGLWidget, change the focus policy to setFocusPolicy(Qt::StrongFocus); and reimplement the paintEvent like this:

    void OpenGLWidget::paintEvent(QPaintEvent *event)
    {
        QOpenGLWidget::paintEvent(event);
    
        QPainter painter(this);
    
        painter.setPen(QPen(QBrush(Qt::magenta), 2));
    
        if (hasFocus())
            painter.drawRect(QRect(1, 1, width() - 2, height() - 2));
    }
    

    Example

    In order to demonstrate how to implement that in an application I have prepared a working example for you. The code is available on GitHub.

    Result

    This will give you a nice purple border at the edge of the clicked view:

    enter image description here