• Qt去掉view项的焦点虚线框的方法(转)


    Qt中的view类,如QListView, 在其项被选中时会有一个焦点虚线框表示焦点的位置。 不知道为啥,这个焦点虚线框很不招人待见, 笔者至今已经遇到多例想要去掉该虚线框的问题。

    笔者能想到的有两个方法, memo如下:
    使用QItemDelegate子类
    对QItemDelegate这个类笔者在此不多做讨论, 详情参考Qt文档。 简单来说,这个类可以控制view中的项的绘制方式,其中包括焦点虚线框的绘制。 而且焦点虚线框的绘制被封装在一个虚函数中, 所以通过派生QItemDelegate就可以重新定义该函数的功能 — 如什么都不画。 具体对应的虚函数是:
    http://qt.nokia.com/doc/4.6/qitemdelegate.html#drawFocus

    有了QItemDelegate的子类后,我们需要调用QAbstractItemView的setItemDelegate方法将我们的item delegate与view关联。 这个itemdelegate可以为view全局有效,或针对某个item, 也可以调用setItemDelegateForRow/Column设置针对行或列有效的delegate。

    使用QStyle子类
    这个方法的作用原理和第一种方法基本一致, 因为QItemDelegate的drawFocus函数调用QStyle的drawPrimitive虚函数去做实际的绘制, 所以如果我们重新定义这个绘制过程能达到同样的效果。 drawPrimitive函数负责绘制非常基本的界面元素, 根据传入的参数判断需要绘制的元素, 具体到本例就是要针对PE_FrameFocusRect元素做特殊处理。 例子代码如下:

    class NoFocusRectangleStyle: public QCommonStyle
    {
    public:
    ...
    void NoFocusRectangleStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option,
    QPainter *painter, const QWidget *widget) const
    {
    if (QStyle::PE_FrameFocusRect == element && widget && widget->inherits("QListWidget"))
    return;
    else
    QCommonStyle::drawPrimitive(element, option, painter,
    widget);
    }
    };

    一般我们派生QStyle不会傻乎乎地去派生这个基本的基类, 更常见的是派生与我们需要的风格最接近的类,一般是我们的程序默认使用的类。 我们的派生类可能非常简单, 只重写drawPrimitive这么一个函数, 几行代码搞定。 使用方法是调用QApplication::setStyle, 或者QWidget::setStyle, 前者将style效果应用到程序中的所有窗体,后者将效果限制在当前窗体。

    小小memo, 希望对广大Qter有所帮助。 如果大家有其他方法欢迎留言。

     
    其他:
    /* This class will be used to remove the dotted lines when table item selected*/
    /** class GridDelegateLayout */
    class GridDelegateLayout: public QItemDelegate
    {
    public:
        GridDelegateLayout (): QItemDelegate ()
        {
        }
        void drawFocus (QPainter *pPainter, const QStyleOptionViewItem& option,
                        const QRect& rRect) const
        {
            Q_UNUSED (rRect)
            if (option.state & QStyle::State_HasFocus)
            {
                QPen penVal (Qt::white);
                penVal.setWidth (0);
                pPainter->setPen (penVal);
                // painter->drawRect(rect);
            }
        }
    };
  • 相关阅读:
    ACM模板——次短路及K短路
    ACM模板——最小生成树
    Leetcode-743 Network Delay Time(网络延迟时间)
    ACM模板——最短路
    HDU-2037 今年暑假不AC
    Leetcode-1015 Numbers With Repeated Digits(至少有 1 位重复的数字)
    Leetcode-1014 Capacity To Ship Packages Within D Days(在 D 天内送达包裹的能力)
    Leetcode-1013 Pairs of Songs With Total Durations Divisible by 60(总持续时间可被 60 整除的歌曲)
    Leetcode-1012 Complement of Base 10 Integer(十进制整数的补码)
    LeetCode--204--计数质数
  • 原文地址:https://www.cnblogs.com/veins/p/3209797.html
Copyright © 2020-2023  润新知