qt(4)QLineEdit之文本不被选中

http://blog.sina.com.cn/s/blog_a6fb6cc90101b3b8.html

转自上面,分析得很到位。

文本被选中状态有以下几种情况:

1、全选(Ctrl+A)

2、鼠标双击(频繁点击)

3、Shift + Home 组合键

4、Shift + End 组合键

5、Shift + 鼠标点击

6、Tab键切换

7、左、右键

。。。


8,鼠标右键

void PwdLineEdit::contextMenuEvent(QContextMenuEvent *event)
{
    if(event->reason()== QContextMenuEvent::Mouse)
    {
        focusPreviousChild();

        return;
    }
}


涉及的知识点:

1,qt自定义部件,然后在qtdesigner中把对应的部件提升下,

2,重写一些部件的事件函数

void PwdLineEdit::mouseDoubleClickEvent(QMouseEvent *)
{
    return;
}
void PwdLineEdit::mouseMoveEvent(QMouseEvent *)
{
    return;
}
void PwdLineEdit::keyPressEvent(QKeyEvent *event)
{
    if(event->matches(QKeySequence::Copy))
    {
        return;
    }
    else if(event->matches(QKeySequence::SelectAll))
    {
        return;
    }
    else if(event->matches(QKeySequence::Paste))
    {
        return;
    }
    else if(event->key() == Qt::Key_Home)
    {
        this->setCursorPosition(0);
    }
    else if(event->key() == Qt::Key_End)
    {
        this->setCursorPosition(this->text().length());
    }
    else{
        QLineEdit::keyPressEvent(event);
    }

}
void PwdLineEdit::mousePressEvent(QMouseEvent *event)
{
    //鼠标位置
    int curMousePos = cursorPositionAt(event->pos());
    //光标位置
    int curCursorPos = this->cursorPosition();
    if(curMousePos < curCursorPos)
    {
        this->setCursorPosition(curCursorPos-1);
    }
    else if(curMousePos < curMousePos)
    {
        this->setCursorPosition(curCursorPos+1);
    }else
    {
        QLineEdit::mousePressEvent(event);
    }
}

3,事件过滤器

bool loginDlg::eventFilter(QObject *obj, QEvent *event)
{
    if(obj == ui->nameEdit&& event->type() == QEvent::KeyPress)
    {
        QKeyEvent* keyevent = static_cast(event);
        if(keyevent->key() == Qt::Key_Tab)
        {
            focusNextChild();
            int len = ui->pwdEdit->text().length();
            ui->pwdEdit->setSelection(len,len);
            ui->pwdEdit->setFocus();
            return true;
        }else return false;
    }
    else return false;
}


你可能感兴趣的:(Qt)