qlineedit校验输入合法性,弹出错误提示框

不解释题目,直接上效果图:


做法与思路:

1.错误图标和”名称不合法“这几个字都是显示在一个qlabel中的,但是这不是一个简单的label,必须继承自qlabel,并重写paintevent()函数,如下所示:

void CWellLogLabel::paintEvent(QPaintEvent *pEvent)
{
QPainter painter(this);


QFontMetrics fontMetrics(font());
QPixmap errPixmap(::GetImagePath()+ "error.png");
painter.drawPixmap(0, (this->height()-errPixmap.height())/2, errPixmap);


painter.setPen(Qt::red);
QString showText = fontMetrics.elidedText(text(),Qt::ElideRight,width()-errPixmap.width());
painter.drawText(rect().adjusted(errPixmap.width() + 3, 0, 0, 0),
Qt::AlignVCenter | Qt::AlignLeft, showText);


}

2.在dialog的构造函数里面,窗口布局中添加此label,并设置为不可见,最后还要获取名称编辑结束的信号,进行处理:

m_pLabel = new CWellLogLabel;
m_pLabel->setVisible(false);
m_pUI->horizontalLayout->addWidget(m_pLabel);
connect(m_pUI->ProjectName,SIGNAL(editingFinished()),this,SLOT(slotOnEditFinished() ));

3.最后写编辑结束信号的响应槽进行校验操作

void CWellLogProjectDialog::slotOnEditFinished()
{
QFont wordfont;
wordfont.setFamily("宋体");
wordfont.setPointSize(10);
QFontMetrics fm(wordfont);
m_pLabel->setText("名称不合法");
QRect rec = fm.boundingRect( m_pLabel->text());
int ii = rec.width();
m_pLabel->setFixedWidth(rec.width() + 16);
m_pLabel->setVisible(true);//一定要重新设置为可见
//QMessageBox::information(NULL,"提示","lfjlasfjolasfjapolsfasp");
}

你可能感兴趣的:(qlineedit校验输入合法性,弹出错误提示框)