源码下载地址:https://gitee.com/Ailsc/Duilib

在实际过程中我们经常需要实现edit的占位文本提示,如下

Duilib Edit占位提示文本实现_提示文字


实现原理:当edit为空的时候,则展示占位文本。

DWORD m_dwPlaceholderTexeColor;
CDuiString m_sPlaceholderText;
void CEditUI::SetPlaceholderText(LPCTSTR pstrText)
{
if (m_sPlaceholderText == pstrText) return;
m_sPlaceholderText = pstrText;
if (m_sText.IsEmpty())
{
Invalidate();
}
}

void CEditUI::SetPlaceholderTextColor(DWORD dwColor)
{
if (m_dwPlaceholderTexeColor == dwColor) return;
m_dwPlaceholderTexeColor = dwColor;
if (m_sText.IsEmpty())
{
Invalidate();
}
}

重写paintText实现:

void CEditUI::PaintText(HDC hDC)
{
if( m_dwTextColor == 0 ) m_dwTextColor = m_pManager->GetDefaultFontColor();
if( m_dwDisabledTextColor == 0 ) m_dwDisabledTextColor = m_pManager->GetDefaultDisabledColor();

if (m_sText.IsEmpty() && m_sPlaceholderText.IsEmpty()) return;

DWORD dwTextColor = m_sText.IsEmpty() ? m_dwDisabledTextColor : m_dwTextColor;
CDuiString drawText = m_sText.IsEmpty() ? m_sPlaceholderText : m_sText;
CDuiString sText = drawText;
if (m_bPasswordMode && !m_sText.IsEmpty()) {
sText.Empty();
LPCTSTR p = drawText.GetData();
while( *p != _T('\0') ) {
sText += m_cPasswordChar;
p = ::CharNext(p);
}
}

RECT rc = m_rcItem;
rc.left += m_rcTextPadding.left;
rc.right -= m_rcTextPadding.right;
rc.top += m_rcTextPadding.top;
rc.bottom -= m_rcTextPadding.bottom;
if( IsEnabled() ) {
CRenderEngine::DrawText(hDC, m_pManager, rc, sText, dwTextColor, \
m_iFont, DT_SINGLELINE | m_uTextStyle);
}
else {
CRenderEngine::DrawText(hDC, m_pManager, rc, sText, m_dwDisabledTextColor, \
m_iFont, DT_SINGLELINE | m_uTextStyle);

}
}

实现属性设置:SetAttribute

else if (_tcscmp(pstrName, _T("placeholdertext")) == 0) SetPlaceholderText(pstrValue);
else if (_tcscmp(pstrName, _T("placeholdertextcolor")) == 0) {
if (*pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetPlaceholderTextColor(clrColor);
}
else CLabelUI::SetAttribute(pstrName, pstrValue);

使用:

<Edit name="pass_word" font="6" placeholdertextcolor="#ff9999a9" placeholdertext="请输入身份证号码" bkcolor="#fff2f2f4" nativebkcolor="#fff2f2f4" maxchar="64" padding="3,3,3,3"/>