c++ - 编辑器处于事件状态时呈现的 Qt 委托(delegate)显示文本

标签 c++ qt model-view-controller

我实现了一个单位文本框,它能够在选择不同单位时进行转换。这是通过使用 QHBoxLayout 将 QLineEdit 和 QLabel 粘在一起来完成的。

enter image description here

class LengthTextBox::Impl
{
    public:
        Impl() :
            lblUnit(new QLabel()),
            txtValue(new QLineEdit()),
            menuLength(new LengthMenu(lblUnit)),
            precision(2),
            unit(units::Length::Meters)
        {
        }

        QLabel* lblUnit;
        QLineEdit* txtValue;
        LengthMenu* menuLength;

        int precision;

        units::Length unit;
};

LengthTextBox::LengthTextBox(QWidget* parent) : QWidget(parent),
    pimpl()
{
    const auto hLayout = new QHBoxLayout(this);

    // Adjust spacing for better fit within tables.
    const auto spacing = 2;
    auto margins = hLayout->contentsMargins();
    margins.setTop(0);
    margins.setLeft(spacing);
    margins.setRight(spacing);
    margins.setBottom(0);
    hLayout->setContentsMargins(margins);
    hLayout->setSpacing(spacing);

    this->pimpl->txtValue->setValidator(new QDoubleValidator());

    // Install an event filter to capture focus out events.
    this->pimpl->txtValue->installEventFilter(this);

    hLayout->addWidget(this->pimpl->txtValue);
    hLayout->addWidget(this->pimpl->lblUnit);

    // Since we're building on top of a QWidget, set up the focus policies to still focus on the text box.
    this->setFocusProxy(this->pimpl->txtValue);
    this->pimpl->txtValue->setFocusPolicy(Qt::StrongFocus);
    this->pimpl->lblUnit->setFocusPolicy(Qt::ClickFocus);

    // Connect signals for switching between units.
    this->connect(this->pimpl->lblUnit, &QLabel::linkActivated, this, &LengthTextBox::unitSelectorClicked);
    this->connect(this->pimpl->menuLength, &LengthMenu::unitChanged, this, &LengthTextBox::setUnit);

    // Forward the line edit signals.
    this->connect(this->pimpl->txtValue, &QLineEdit::editingFinished, this, &LengthTextBox::editingFinished);
    this->connect(this->pimpl->txtValue, &QLineEdit::returnPressed, this, &LengthTextBox::returnPressed);
    this->connect(this->pimpl->txtValue, &QLineEdit::textChanged, this, &LengthTextBox::textChanged);
    this->connect(this->pimpl->txtValue, &QLineEdit::textEdited, this, &LengthTextBox::textEdited);

    this->setUnit(this->pimpl->unit);
}

LengthTextBox::~LengthTextBox()
{
}

void LengthTextBox::setPrecision(int x)
{
    this->pimpl->precision = x;
}

int LengthTextBox::getPrecision() const
{
    return this->pimpl->precision;
}

void LengthTextBox::setUnit(const units::Length& x)
{
    const auto value = this->getValue();
    this->setValue(units::Convert(value, this->pimpl->unit, x));

    // Use HTML to render the text as a link. This will lead to the linkActivated signal when clicked.
    const QString link = "<b><a href='#'>" + QString::fromStdString(units::GetSymbol(x)) + "</a></b>";
    this->pimpl->lblUnit->setText(link);

    this->pimpl->txtValue->setFocus(Qt::FocusReason::OtherFocusReason);
    this->pimpl->txtValue->selectAll();

    this->pimpl->unit = x;
    this->unitChanged(this->pimpl->unit);
}

units::Length LengthTextBox::getUnit() const
{
    return this->pimpl->unit;
}

void LengthTextBox::setValue(double x, const units::Length& fromUnit)
{
    if(fromUnit != units::Length::Unknown)
    {
        x = units::Convert(x, fromUnit, this->pimpl->unit);
    }

    this->pimpl->txtValue->setText(QString::number(x, 'f', this->pimpl->precision));
}

double LengthTextBox::getValue(const units::Length& toUnit) const
{
    auto value = this->pimpl->txtValue->text().toDouble();

    if(toUnit != units::Length::Unknown)
    {
        value = units::Convert(value, this->pimpl->unit, toUnit);
    }

    return value;
}

std::string LengthTextBox::getFormattedText() const
{
    return this->pimpl->txtValue->text().toStdString() + " " + units::GetSymbol(this->pimpl->unit);
}

void LengthTextBox::unitSelectorClicked()
{
    this->pimpl->menuLength->popup(QCursor::pos());
}

bool LengthTextBox::eventFilter(QObject* obj, QEvent* x)
{
    // Watch for a focus out event on the text box inorder to send a lost focus signal.
    if(this->pimpl->txtValue == obj)
    {
        if(x->type() == QEvent::FocusOut && this->pimpl->lblUnit->hasFocus() == false)
        {
            this->lostFocus();
            return true;
        }
    }

    return QWidget::eventFilter(obj, x);
}

接下来,我派生了一个 QStyledItemDelegate,这样我就可以在我自己的 QTableView 中使用这个文本框。 enter image description here

如果仔细观察,您会发现当编辑器在此委托(delegate)上处于事件状态时,字母“m”呈现在超链接“m”后面。

class LengthTextBoxDelegate::Impl
{
    public:
        Impl(int precision) :
            txtLength(std::make_unique<LengthTextBox>())
        {
            this->txtLength->setPrecision(precision);
        }

        // By using a length text box to manage current selected unit, all conversion logic remains in one place.
        std::unique_ptr<LengthTextBox> txtLength;
};

LengthTextBoxDelegate::LengthTextBoxDelegate(int precision, QWidget* parent) : QStyledItemDelegate(parent),
    pimpl(precision)
{
}

LengthTextBoxDelegate::~LengthTextBoxDelegate()
{
}

QString LengthTextBoxDelegate::displayText(const QVariant& value, const QLocale&) const
{
    this->pimpl->txtLength->setValue(value.toDouble(), Length::Meters);
    return QString::fromStdString(this->pimpl->txtLength->getText()) + " " + QString::fromStdString(GetSymbol(this->pimpl->txtLength->getSelectedUnit()));
}

QWidget* LengthTextBoxDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem&, const QModelIndex& index) const
{
    const auto txtLength = new LengthTextBox(parent);
    txtLength->setValue(index.data().toDouble());
    txtLength->setSelectedUnit(this->pimpl->txtLength->getSelectedUnit());
    txtLength->setPrecision(this->pimpl->txtLength->getPrecision());

    // AMS // This is kind of a hack. For some reason, the ::displayText() that is rendered when no editor is created, was getting rendered
    // behind the editor widget and was appearing through as if the text box was transparent.
    // By setting the background color white, we get a nice aesthetic that matches the table views that use this delegate.
    // In addition, it covers up the text that was appearing behind the widget.
    auto p = txtLength->palette();
    p.setColor(QPalette::Base, Qt::white);
    txtLength->setPalette(p);
    //txtLength->setAutoFillBackground(true);

    // Track the current unit so that its symbol can be rendered when ::displayText() is called.
    this->connect(txtLength, &LengthTextBox::unitChanged, this, &LengthTextBoxDelegate::unitChanged);
    this->connect(txtLength, &LengthTextBox::returnPressed, this, &LengthTextBoxDelegate::commitAndCloseEditor);
    this->connect(txtLength, &LengthTextBox::lostFocus, this, &LengthTextBoxDelegate::commitAndCloseEditor);

    return txtLength;
}

void LengthTextBoxDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const
{
    const auto txtLength = qobject_cast<LengthTextBox*>(editor);
    assert(txtLength != nullptr);

    txtLength->setValue(index.data().toDouble(), Length::Meters);
}

void LengthTextBoxDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
    const auto txtLength = qobject_cast<LengthTextBox*>(editor);
    assert(txtLength != nullptr);

    model->setData(index, txtLength->getValue(Length::Meters));
}

void LengthTextBoxDelegate::unitChanged(const hive::math::units::Length& x)
{
    this->pimpl->txtLength->setSelectedUnit(x);
}

void LengthTextBoxDelegate::commitAndCloseEditor()
{
    const auto txtLength = qobject_cast<LengthTextBox*>(this->sender());
    this->commitData(txtLength);
    this->closeEditor(txtLength);
}

到目前为止,我想出的唯一解决方案是在我的编辑器小部件上设置背景颜色。这感觉很糟糕,一定是我做错了什么。

enter image description here

有没有办法在我的编辑器处于事件状态时阻止呈现 Qt::DisplayRole 文本?

最佳答案

您需要在绘制编辑器小部件之前填充背景QWidgetautoFillBackground属性控制此行为,因为它默认设置为 false,您的编辑器小部件将绘制在 QTableView 上。

您只需要在返回之前在 createEditor() 中设置编辑器的属性:

txtLength->setAutoFillBackground(true);

背景颜色使用 setBackgroundRole() 指定,它默认继承父级的背景(如果父级是 QTableView,则为 QPalette::Base)。因此,您将获得编辑器的白色背景,您可能需要指定 QPalette::Window 颜色角色:

txtLength->setBackgroundRole(QPalette::Window);

关于c++ - 编辑器处于事件状态时呈现的 Qt 委托(delegate)显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40997498/

相关文章:

c++ - 依赖模板函数的 Pimpl 习语实现

c++ - 如何在 macOS 上的 Qt 中使用 OpenMP 进行编译?

java - 当 Docker 容器中的 Java MVC 应用程序尝试连接到另一个容器中的 MySQL 时出现表不存在错误

javascript - 使用 JQuery 更改 img src 但完整保留路径信息?

c++ - x86-64 长 double

c++ - OpenCV:对 xcb_poll_for_reply 的 undefined reference

C++ 常量转换

c++ - 在 C++ (Qt) 中实现内省(introspection)

c++ - Qt 构建顺序(rcc -> uic -> moc -> 预处理器 -> 普通编译器)?

Java MVC - 感觉我不明白