Skip to content

Conversation

@caixr23
Copy link
Contributor

@caixr23 caixr23 commented Nov 5, 2025

The control resizes based on its content

pms: BUG-327527

Summary by Sourcery

Refactor NetTipsWidget to dynamically adjust its label height based on HTML content and font changes, fixing incorrect resizing.

Bug Fixes:

  • Ensure NetTipsWidget control resizes to fit its HTML content and updates on name or font changes

Enhancements:

  • Extract height calculation into a dedicated updateHeight() method and connect it to nameChanged signal
  • Override event() to recalculate height on QEvent::FontChange
  • Replace inline QLabel with member variable m_label and set top-left alignment

@sourcery-ai
Copy link

sourcery-ai bot commented Nov 5, 2025

Reviewer's Guide

Refactor NetTipsWidget to dynamically resize based on its content and font changes by extracting height-calculation logic into a member function, storing the label as a class member, handling QEvent::FontChange, and updating includes.

Sequence diagram for dynamic resizing on font change in NetTipsWidget

sequenceDiagram
participant "QGuiApplication"
participant "NetTipsWidget"
participant "QEvent"
participant "QLabel"
QGuiApplication->>NetTipsWidget: Font change event
NetTipsWidget->>NetTipsWidget: event(QEvent::FontChange)
NetTipsWidget->>NetTipsWidget: updateHeight()
NetTipsWidget->>QLabel: setFixedHeight(newHeight)
NetTipsWidget->>QLabel: setText(updatedText)
Loading

Class diagram for updated NetTipsWidget structure

classDiagram
class NetTipsWidget {
    +NetTipsWidget(NetTipsItem *item, QWidget *parent)
    +~NetTipsWidget()
    +protected bool event(QEvent *event) override
    +protected void updateHeight()
    -QLabel *m_label
}
NetTipsWidget --|> NetWidget
NetAirplaneModeTipsWidget --|> NetTipsWidget
Loading

File-Level Changes

Change Details Files
Refactor label creation and height-update mechanism
  • Replaced local QLabel with member m_label
  • Extracted inline height calculation lambda into NetTipsWidget::updateHeight
  • Swapped connect calls to use the updateHeight method
  • Changed setCentralWidget(label) to setCentralWidget(m_label)
net-view/window/private/netdelegate.cpp
net-view/window/private/netdelegate.h
Handle dynamic font changes via event override
  • Added event(QEvent*) override in NetTipsWidget
  • On QEvent::FontChange, call updateHeight
  • Removed connect to qApp fontChanged signal
net-view/window/private/netdelegate.cpp
net-view/window/private/netdelegate.h
Update and reorder includes
  • Added QTextDocument and QTextLine includes in cpp
  • Added QLabel include in header
  • Reorganized include order for clarity
net-view/window/private/netdelegate.cpp
net-view/window/private/netdelegate.h

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • Avoid the hardcoded width constant (294) in updateHeight—derive the layout width from the widget or label’s actual width instead of using a magic number.
  • You can simplify the height calculation by using QTextDocument::setTextWidth and document.size().height() rather than manual line-by-line QFontMetrics/drawText logic.
  • The include appears unused in the new implementation—consider removing it to clean up the headers.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Avoid the hardcoded width constant (294) in updateHeight—derive the layout width from the widget or label’s actual width instead of using a magic number.
- You can simplify the height calculation by using QTextDocument::setTextWidth and document.size().height() rather than manual line-by-line QFontMetrics/drawText logic.
- The <QTextLine> include appears unused in the new implementation—consider removing it to clean up the headers.

## Individual Comments

### Comment 1
<location> `net-view/window/private/netdelegate.cpp:702` </location>
<code_context>
-        option.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
-        layout.setTextOption(option);
-        QFontMetrics fm(label->font());
-        int line = drawText(nullptr, QRectF(QPointF(0, 0), QSizeF(294, INT_MAX)), fm.boundingRect(plainText).height(), &layout, Qt::ElideNone);
-        label->setFixedHeight(line * fm.boundingRect(plainText).height());
-        label->setText(item->tipsLinkEnabled() ? name : plainText);
</code_context>

<issue_to_address>
**suggestion:** Hardcoded width value (294) may reduce flexibility.

Consider making the width value configurable or dynamically based on the widget's actual width to ensure proper scaling with different UI sizes and fonts.

Suggested implementation:

```cpp
        int availableWidth = label->width() > 0 ? label->width() : label->sizeHint().width();
        int line = drawText(nullptr, QRectF(QPointF(0, 0), QSizeF(availableWidth, INT_MAX)), fm.boundingRect(plainText).height(), &layout, Qt::ElideNone);

```

If this code is called before the label is shown and its width is not set, you may need to ensure the label has a valid width (e.g., by calling this after layout or using a default value). If you want to make the width configurable, you could add a member variable or a setter method to allow external configuration.
</issue_to_address>

### Comment 2
<location> `net-view/window/private/netdelegate.cpp:718-721` </location>
<code_context>
+    layout.setTextOption(option);
+    QFontMetrics fm(m_label->font());
+    int line = drawText(nullptr, QRectF(QPointF(0, 0), QSizeF(294, INT_MAX)), fm.boundingRect(plainText).height(), &layout, Qt::ElideNone);
+    m_label->setFixedHeight(line * fm.boundingRect(plainText).height());
+    m_label->setText(item->tipsLinkEnabled() ? name : plainText);
+}
</code_context>

<issue_to_address>
**suggestion:** Height calculation may not account for line spacing or font metrics nuances.

Using fm.boundingRect(plainText).height() may not yield accurate results for all fonts. For better precision, use QFontMetrics::lineSpacing() or QTextLayout's line metrics to calculate the required label height.

```suggestion
    QFontMetrics fm(m_label->font());
    layout.beginLayout();
    int totalHeight = 0;
    int lineCount = 0;
    while (true) {
        QTextLine textLine = layout.createLine();
        if (!textLine.isValid())
            break;
        textLine.setLineWidth(294);
        totalHeight += textLine.height();
        ++lineCount;
    }
    layout.endLayout();
    // Add extra spacing for each line except the last
    if (lineCount > 1) {
        totalHeight += (lineCount - 1) * fm.lineSpacing();
    }
    m_label->setFixedHeight(totalHeight);
    m_label->setText(item->tipsLinkEnabled() ? name : plainText);
```
</issue_to_address>

### Comment 3
<location> `net-view/window/private/netdelegate.cpp:706` </location>
<code_context>
+    return NetWidget::event(event);
+}
+
+void NetTipsWidget::updateHeight()
+{
+    NetTipsItem *item = static_cast<NetTipsItem *>(this->item());
</code_context>

<issue_to_address>
**issue (complexity):** Consider replacing manual text layout logic with QLabel's built-in rich text and sizing features for updateHeight().

```cpp
// In NetTipsWidget.hpp, drop the manual QTextDocument/QTextLayout includes:
-#include <QTextDocument>
-#include <QTextLine>

// Replace your heavy updateHeight() with QLabel’s built-ins:
void NetTipsWidget::updateHeight()
{
    auto *item = static_cast<NetTipsItem *>(this->item());
    const QString name = item->name();

    // If you need rich‐text links, tell QLabel to interpret HTML:
    m_label->setTextFormat(Qt::RichText);
    m_label->setText(item->tipsLinkEnabled() ? name : name.toPlainText());

    // Constrain width and let QLabel word-wrap + sizeHint fix the height:
    constexpr int maxW = MAX_TEXT_WIDTH;
    m_label->setFixedWidth(maxW);
    m_label->setWordWrap(true);
    m_label->adjustSize();
}

// You can now remove all of your QTextDocument/QTextLayout/drawText logic.
// You still connect:
connect(item, &NetTipsItem::nameChanged,   this, &NetTipsWidget::updateHeight);
connect(qApp,&QGuiApplication::fontChanged,this, &NetTipsWidget::updateHeight);

// And you can also drop the custom event() override if you rely on
// QGuiApplication::fontChanged instead of catching QEvent::FontChange.
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@deepin-ci-robot
Copy link

deepin pr auto review

我来分析一下这段代码的修改:

  1. 代码结构改进:
  • 将原来的局部变量 label 改为类成员变量 m_label,这是一个好的实践,提高了代码的可维护性
  • 将原来的 lambda 函数 updateHeight 拆分为成员函数,使代码结构更清晰
  • 添加了 event() 函数来处理字体变化事件
  1. 代码质量建议:
  • 在 updateHeight() 函数中,建议增加对 item 的空指针检查,避免潜在的崩溃风险
  • 建议将魔数 294 和 INT_MAX 定义为常量,提高代码可读性
  • 在 event() 函数中,应该先判断父类的 event() 返回值,而不是直接返回
  1. 性能优化建议:
  • 在 updateHeight() 函数中,每次都重新创建 QTextDocument 和 QTextLayout 对象,可以考虑将这些对象作为成员变量复用
  • drawText() 函数可能会被频繁调用,可以考虑缓存计算结果
  1. 安全性建议:
  • 在使用 static_cast 转换 item 时,建议增加类型检查或使用 dynamic_cast 并检查返回值

改进后的代码示例:

class NetTipsWidget : public NetWidget
{
private:
    static constexpr int DEFAULT_WIDTH = 294;
    
    QLabel *m_label;
    QTextDocument m_textDocument;
    QTextLayout m_textLayout;

protected:
    bool event(QEvent *event) override {
        if (event->type() == QEvent::FontChange) {
            updateHeight();
        }
        return NetWidget::event(event);
    }

    void updateHeight() {
        NetTipsItem *item = dynamic_cast<NetTipsItem*>(this->item());
        if (!item) return;

        const QString &name = item->name();
        m_textDocument.setHtml(name);
        const QString &plainText = m_textDocument.toPlainText();
        
        m_textLayout.setText(plainText);
        m_textLayout.setFont(m_label->font());
        
        QTextOption option;
        option.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
        option.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        m_textLayout.setTextOption(option);
        
        QFontMetrics fm(m_label->font());
        int line = drawText(nullptr, QRectF(QPointF(0, 0), QSizeF(DEFAULT_WIDTH, INT_MAX)), 
                          fm.boundingRect(plainText).height(), &m_textLayout, Qt::ElideNone);
        m_label->setFixedHeight(line * fm.boundingRect(plainText).height());
        m_label->setText(item->tipsLinkEnabled() ? name : plainText);
    }
};

这些改进提高了代码的健壮性、可维护性和性能,同时保持了原有功能的完整性。

@caixr23 caixr23 requested a review from mhduiy November 5, 2025 06:43
@deepin-ci-robot
Copy link

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: caixr23, mhduiy

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

The control resizes based on its content

pms: BUG-327527
@caixr23 caixr23 merged commit e5a9b0b into linuxdeepin:master Nov 6, 2025
11 of 13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants