shelllet / cpp-example

c++ examples
24 stars 7 forks source link

About QStyledItemDelegate #1

Open stephensyn opened 4 years ago

stephensyn commented 4 years ago

为了在TableView中格式化显示信息,重写了delegate的: void paint(QPainter* painter,const QStyleOptionViewItem& option,const QModelIndex& index) const; 结果: 1、实现了想要的格式。 问题: 1、重绘过的Item单元不能被点击(未重绘时,点击Item会变为蓝底黑字,重绘后点击无变化,任然为)

stephensyn commented 4 years ago

接续上面: 白底黑字); 后来添加如下代码: if (option.state &QStyle::State_Selected) { painter->fillRect(option.rect, option.palette.highlight()); QApplication::style()->drawControl(QStyle::CE_CheckBox,&checkBoxStyleOption,painter); } else { QApplication::style()->drawControl(QStyle::CE_CheckBox,&checkBoxStyleOption,painter); } 解决了不能点击选择的问题。不过又出现新的问题: 当点击选择后变为了蓝底黑字后。如果这时焦点转到别的控件后,Item任然还是蓝底黑字。我希望这种情况下Item变为灰底黑字(像系统默认的那种效果)。

stephensyn commented 4 years ago

为了在TableView中格式化显示信息,重写了delegate的: void paint(QPainter* painter,const QStyleOptionViewItem& option,const QModelIndex& index) const; 结果: 1、实现了想要的格式。 问题: 1、重绘过的Item单元不能被点击(未重绘时,点击Item会变为蓝底黑字,重绘后点击无变化,任然为白底黑字); 后来添加如下代码: if (option.state &QStyle::State_Selected) { painter->fillRect(option.rect, option.palette.highlight()); QApplication::style()->drawControl(QStyle::CE_CheckBox,&checkBoxStyleOption,painter); } else { QApplication::style()->drawControl(QStyle::CE_CheckBox,&checkBoxStyleOption,painter); } 解决了不能点击选择的问题。不过又出现新的问题: 当点击选择后变为了蓝底黑字后。如果这时焦点转到别的控件后,Item任然还是蓝底黑字。我希望这种情况下Item变为灰底黑字(像系统默认的那种效果)。)

stephensyn commented 4 years ago

图片

stephensyn commented 4 years ago

以上为选择时

stephensyn commented 4 years ago

以下为焦点离开后

stephensyn commented 4 years ago

图片

stephensyn commented 4 years ago

希望的状态是焦点离开后:蓝底黑字,变为灰底黑字(系统默认的模式)

shelllet commented 4 years ago

image 你可以尝试重绘其它几种状态,比如上面圈起来的

stephensyn commented 4 years ago

谢谢,我试试。

stephensyn commented 4 years ago

添加了state &QStyle::State_Active的重绘,完美实现。 ` QStyleOptionButton checkBoxStyleOption; checkBoxStyleOption.state |= QStyle::State_Enabled; checkBoxStyleOption.state |= checked? QStyle::State_On : QStyle::State_Off; checkBoxStyleOption.rect = CheckBoxRect(option);

            if (option.state &QStyle::State_Selected )
            {                  
                  painter->fillRect(option.rect, option.palette.highlight());
                  if(option.state &QStyle::State_Active)
                  {

                  }
                  else
                  {
                     painter->fillRect(option.rect, option.palette.button());
                  }

            }
            else
            {

            }

      QApplication::style()->drawControl(QStyle::CE_CheckBox,&checkBoxStyleOption,painter);

}`
stephensyn commented 4 years ago

QApplication::style()->drawItemText ( painter, myOption.rect , myOption.displayAlignment,QApplication::palette(),true,text); 请问这个语句在重绘文本时在参数里能指定文本颜色吗?

stephensyn commented 4 years ago

图片

重绘的文本是黑色。怎样指定参数设置成白色字体呢?谢谢老师

shelllet commented 4 years ago

painter 指针 和 palette 这两个都可以指定颜色