简体   繁体   中英

Change background color of QLabel when hovered in Qt

I have 4 QLabels in 5 rows and when I hover on any QLabel, all the QLabels in that row needs to change the background color.

I am new to Qt. I searched about it and found that it is possible if we make a subclass of QLabel and use Mouse Events. Can anyone explain how to do this?

A possibility: Install an event filter on each QLable instance:

 for(auto label : this->labels){
    label->installEventFilter(this);
}

Then override the event filter function of this. You can now catch any event from any QLabel and change the background:

bool MyWidget::eventFilter(QObject *watched, QEvent *event){

    if(labels.contains((QLabel*)watched)){
        if(event->type() == QEvent::Enter){

            for(auto label: this->labels){
                label->setStyleSheet("background-color: red");
            }
        }else if(event->type() == QEvent::Leave){

            for(auto label: this->labels){
               label->setStyleSheet("");
            }
        }
    }

    return false;
}

I used the mouse enter and leave events. If the mouse over any label the background of all labels changed to red.

If you use a QGridLayout

Install event filter for all QLabel intances:

QList<QLabel*> labels;
labels << this->findChildren<QLabel*>();

for(auto lable : labels){
    lable->installEventFilter(this);
}

Now determine the row of the event source and change the background of all widgets in the column:

bool MyWidget::eventFilter(QObject *watched, QEvent *event){

    if(event->type() == QEvent::Enter || event->type() == QEvent::Leave){

        QLabel* label = static_cast<QLabel*>(watched);

        int index = this->ui->gridLayout->indexOf(label);

        // determine the row
        int row, column, rowSpan, columnSpan;
        this->ui->gridLayout->getItemPosition(index, &row, &column, &rowSpan, &columnSpan);

        // for each elemet in row
        for(column = 0 ; column < this->ui->gridLayout->columnCount() ; column++ ){

            QLayoutItem* item = this->ui->gridLayout->itemAtPosition(row, column);
            if(item == nullptr) continue;

            QLabel* lable = dynamic_cast<QLabel*>(item->widget());
            if(label == nullptr) continue;

            lable->setStyleSheet(event->type() == QEvent::Enter ? "background-color: red" : "");
        }

    }

    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM