学习实现计算器中,点击一个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,则此控件不产生焦点。