Qt重写:QLineEdit可以设置占位文本的颜色

环境

系统:Windows10 64位 家庭中文版
Qt版本:5.6.0 msvc2013 64位
编译器:Visual Studio 2013 专业版

目的

重写QLineEdit,在保留原QLineEdit功能的基础上,实现占位文本颜色的设置。

方法

1.新建一个类,此类继承于QLineEdit;
2.重写此类的paintEvent(QPaintEvent *event)。

关键代码

1.绘制文本

//绘制文本------------------------------
//构建绘制文本的矩形     
QRect textRect;                                 
textRect.setX(0);
textRect.setY((this->height() - textHeight) / 2);
textRect.setWidth(this->width());
textRect.setHeight(textHeight);
//根据要绘制的内容,设置文本和颜色 
QString drawText = QString("");
if (!this->displayText().isEmpty())
{
    painter.setPen(QPen(m_textColor));
    drawText = this->displayText();
}
else if (!this->placeholderText().isEmpty())
{
    painter.setPen(QPen(m_placeholderTextColor));
    drawText = this->placeholderText();
}
//绘制
painter.drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, drawText);

2.绘制选中背景色

//绘制选择背景,背景得先画,文字才看得清
QFontMetrics fontMetric = painter.fontMetrics(); //获取字体宽度
if (this->hasSelectedText())
{
    //获取选中文本的起点
    int selectStart = this->selectionStart();
    int xPos = fontMetric.boundingRect(this->displayText()
             .mid(0, selectStart)).width() + 1;
    //构建绘制矩形
    QRect backRect;
    backRect.setX(xPos);
    backRect.setY((this->height() - textHeight- 1) / 2);
    backRect.setHeight(textHeight + 2);
    backRect.setWidth(fontMetric.width(this->displayText()
         .mid(selectStart, this->selectedText().length())));
    //绘制
    painter.fillRect(backRect, QBrush(m_selectColor));
}

3.绘制光标

//绘制光标
if (hasFocus() && m_bDrawCursor)
{
    int cursorXPos = fontMetric.boundingRect(this->displayText()
          .left(this->cursorPosition())).width() + 1;
    int cursorYPos = (this->height() - textHeight - 1) / 2;
    painter.setPen(QPen(Qt::black));
    painter.drawLine(QPoint(cursorXPos, cursorYPos),
                     QPoint(cursorXPos, cursorYPos + textHeight + 1));
}

示例源码

猜你喜欢

转载自blog.csdn.net/chase_hung/article/details/80864148