【问题标题】:Change background color of QLabel when hovered in Qt在 Qt 中悬停时更改 QLabel 的背景颜色
【发布时间】:2017-06-13 22:22:41
【问题描述】:

我在 5 行中有 4 个 QLabel,当我将鼠标悬停在任何 QLabel 上时,该行中的所有 QLabel 都需要更改背景颜色。

我是 Qt 的新手。我搜索了一下,发现如果我们创建一个 QLabel 的子类并使用鼠标事件是可能的。谁能解释一下如何做到这一点?

【问题讨论】:

  • 请不要要求解释如何执行一般任务,但如果您在实施中遇到问题,请努力并回来。

标签: c++ qt mouseevent subclass qlabel


【解决方案1】:

一种可能性:在每个 QLable 实例上安装一个事件过滤器:

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

然后覆盖this的事件过滤函数。你现在可以赶上 来自任何 QLabel 的任何事件并更改背景:

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;
}

我使用了鼠标进入和离开事件。如果鼠标悬停在任何标签上,所有标签的背景都会变为红色。

如果您使用 QGridLayout

为所有 QLabel 实例安装事件过滤器:

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

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

现在确定事件源所在的行并改变背景 列中的所有小部件:

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;
}

【讨论】:

  • 这将改变所有 QLabels 的背景。但我需要更改该特定行中存在的 Qlabels 的背景。
  • 你使用 QGridLayout 吗?
  • 我使用了 QVBoxLayouts 和 QHBoxLayout
  • 您还可以为目标对象指定特定名称,并且在您的样式表中,您可以为具有这些名称的 QLabel 指定一个特定部分,就像在经典 CSS 中一样...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多