环境
系统:Windows10 64位 家庭中文版
Qt版本:5.6.0 msvc2013 64位
编译器:Visual Studio 2013 专业版
目的
重写QLineEdit,在保留原QLineEdit功能的基础上,实现占位文本颜色的设置。
方法
1.新建一个类,此类继承于QLineEdit;
2.重写此类的paintEvent(QPaintEvent *event)。
关键代码
1.绘制文本
//绘制文本------------------------------
//构建绘制文本的矩形
QRect textRect;
//这两个参数是为了修正光标位置和增加显示文本随光标移动和而移动的功能
int textXpos = 0, textWidth;
if (!this->displayText().isEmpty())
{
textWidth = fontMetric.boundingRect(this->displayText().left(this->cursorPosition())).width();
if (textWidth > this->width())
{
textXpos = this->width() - textWidth - 1;
}
else
{
textWidth = this->width();
}
}
else
{
textXpos = 0;
textWidth = this->width();
}
textRect.setX(textXpos);
textRect.setY((this->height() - textHeight) / 2);
textRect.setWidth(textWidth);
textRect.setHeight(textHeight);
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;
//修正光标位置大于整个LineEdit宽度的情况
if (cursorXPos > this->width())
{
cursorXPos = this->width() - 2;
}
int cursorYPos = (this->height() - textHeight - 1) / 2;
painter.setPen(QPen(Qt::black));
painter.drawLine(QPoint(cursorXPos, cursorYPos),
QPoint(cursorXPos, cursorYPos + textHeight + 1));
}