【问题标题】:Correct highlighting with qt custom delegates使用 qt 自定义委托正确突出显示
【发布时间】:2013-09-02 08:22:45
【问题描述】:

我正在制作一个表格控件,该控件显示除了其模型的 DisplayRole 中的其他文本数据之外的一些其他文本数据。在所有其他方面,文本和单元格显示应该相同。我遇到的问题是正确显示突出显示的单元格。

我目前正在使用以下代码:

void MatchDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{

 if (option.state & QStyle::State_Selected)
      painter->fillRect(option.rect, option.palette.highlight());
 painter->save();
 QString str = qvariant_cast<QString>(index.data())+ "\n";
 str  += QString::number(qvariant_cast<float>(index.data(Qt::UserRole)));
 if (option.state & QStyle::State_Selected)
     painter->setBrush(option.palette.highlightedText());
 else
     painter->setBrush(qvariant_cast<QBrush>(index.data(Qt::ForegroundRole)));

 painter->drawText(option.rect, qvariant_cast<int>(index.data(Qt::TextAlignmentRole)), str);
 painter->restore();

}

但是,结果如下所示:

文本颜色错误,单元格周围没有虚线,当控件失去焦点时,单元格保持蓝色而不是像默认单元格那样变成浅​​灰色。

应该如何更改绘画代码来解决这些问题?

【问题讨论】:

  • 看来,您没有分别设置 QPen .(Pen color and style) white 和 Qt::DashLine。
  • 如何根据调色板设置笔?
  • 调用基类paint..QStyledItemDelegate::paint(painter, option, index);" 可以解决你的问题
  • 我希望重新实现该部分,而不仅仅是使用它。
  • 默认情况下,当您选择一个项目委托时,它将用您的背景突出显示虚线边框和高亮文本

标签: c++ qt user-interface


【解决方案1】:

请尝试下面的代码,它会工作。

选中时设置drawControl,注意绘制虚线(让Qt在内部处理)。

在选择单元格时固定(虚线、文本颜色和多行)。

void MatchDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{         
QStyleOptionViewItemV4 opt = option;
        initStyleOption(&opt, index);

        const QWidget *widget = option.widget;
        QString str = qvariant_cast<QString>(index.data())+ "\n";
         str  += QString::number(qvariant_cast<float>(index.data(Qt::UserRole)));
           opt.text = "";
        //option
        QStyle *style = widget ? widget->style() : QApplication::style();


        if (option.state & QStyle::State_Selected)
        {
            // Whitee pen while selection
            painter->setPen(Qt::white);
            painter->setBrush(option.palette.highlightedText());
            // This call will take care to draw, dashed line while selecting
            style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);
        }
        else
        {
            painter->setPen(QPen(option.palette.foreground(), 0));
            painter->setBrush(qvariant_cast<QBrush>(index.data(Qt::ForegroundRole)));
        }

        painter->drawText(option.rect, qvariant_cast<int>(index.data(Qt::TextAlignmentRole)), str);
    }

【讨论】:

  • 我试过这个。单元格正确突出显示,但由于某种原因,其中带有换行符的字符串未显示在 2 行上。
  • @Srv19 已更新多线程支持。很可能,它会得到解决。
猜你喜欢
  • 2021-02-04
  • 2021-09-06
  • 2017-06-26
  • 2021-04-04
  • 1970-01-01
  • 2011-08-28
  • 1970-01-01
  • 2013-11-26
  • 2023-03-13
相关资源
最近更新 更多