初学QT笔记: 多个QLineEdit之间的焦点设置、切换、获取

学习实现计算器中,点击一个lineEdit后,再点击数字按钮,可以将数据或符号显示在选定的lineEdit中。

bool eventFilter(QObject *, QEvent *);


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    ui->setupUi(this);
    m_iCalFlag = 0;
    m_editFlag = 0;
    ui->firstLineEdit->installEventFilter(this);
    ui->secondLineEdit->installEventFilter(this);
    ui->zeroButton->setFocusPolicy(Qt::NoFocus);
    ui->oneButton->setFocusPolicy(Qt::NoFocus);
    ui->twoButton->setFocusPolicy(Qt::NoFocus);
    //QWidget::setFocusPolicy(Qt::NoFocus);
    //QPushButton::setFocusPolicy(Qt::NoFocus);
    //this->setFocusPolicy(Qt::NoFocus);
 
}
 

/* 判断焦点位置 */
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->firstLineEdit)
    {
        if(event->type() == QEvent::FocusIn)
        {
            QPalette p = QPalette();
            p.setColor(QPalette::Base, Qt::green);
            ui->firstLineEdit->setPalette(p);
            printf("get first focusin \r\n");
            m_editFlag = 1;
        }
        else if(event->type() == QEvent::FocusOut)
        {
            QPalette p= QPalette();
            p.setColor(QPalette::Base, Qt::white);
            ui->firstLineEdit->setPalette(p);
            printf("get first focusout \r\n");
            m_editFlag = 0;
        }
    }
    else if(watched == ui->secondLineEdit)
    {
        if(event->type() == QEvent::FocusIn)
        {
            QPalette p= QPalette();
            p.setColor(QPalette::Base, Qt::green);
            ui->secondLineEdit->setPalette(p);
            printf("get two focusin \r\n");
            m_editFlag = 2;
        }
        else if(event->type() == QEvent::FocusOut)
        {
            QPalette p= QPalette();
            p.setColor(QPalette::Base, Qt::white);
            ui->secondLineEdit->setPalette(p);
            printf("get two focusout \r\n");
            m_editFlag = 0;
        }
    }
    return QWidget::eventFilter(watched, event);
}

 

单个控件分别设置焦点为无焦点即可。

Qt::TabFocus 0x1the widget accepts focus by tabbing.
Qt::ClickFocus 0x2the widget accepts focus by clicking.
Qt::StrongFocus TabFocus | ClickFocus | 0x8the widget accepts focus by both tabbing and clicking. On OS X this will also be indicate that the widget accepts tab focus when in 'Text/List focus mode'.
Qt::WheelFocus StrongFocus | 0x4like Qt::StrongFocus plus the widget accepts focus by using the mouse wheel.
Qt::NoFocus 0 the widget does not accept focus.


尝试了所有的pushbotton一个接口禁用,但是失败了。


在ui界面设置属性中直接设置更方便。

选中控件,在右侧属性栏中找到QWidget->focusPolicy->选择NoFocus,则此控件不产生焦点。

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值