1. 程式人生 > >初學QT筆記: 多個QLineEdit之間的焦點設定、切換、獲取

初學QT筆記: 多個QLineEdit之間的焦點設定、切換、獲取

學習實現計算器中,點選一個lineEdit後,再點選數字按鈕,可以將資料或符號顯示在選定的lineEdit中。

booleventFilter(QObject*,QEvent*);
MainWindow::MainWindow(QWidget*parent):
QMainWindow(parent),
ui(newUi::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);
}

/* 判斷焦點位置 */
boolMainWindow::eventFilter(QObject*watched,QEvent*event)
{
if(watched==ui->firstLineEdit)
{
if(event->type()==QEvent::FocusIn)
{
QPalettep=QPalette();
p.setColor(QPalette::Base,Qt::green);
ui->firstLineEdit->setPalette(p);
printf("getfirstfocusin\r\n");
m_editFlag=1;
}
elseif(event->type()==QEvent
::FocusOut)
{
QPalettep=QPalette();
p.setColor(QPalette::Base,Qt::white);
ui->firstLineEdit->setPalette(p);
printf("getfirstfocusout\r\n");
m_editFlag=0;
}
}
elseif(watched==ui->secondLineEdit)
{
if(event->type()==QEvent::FocusIn)
{
QPalettep=QPalette();
p.setColor(QPalette::Base,Qt::green);
ui->secondLineEdit->setPalette(p);
printf("gettwofocusin\r\n");
m_editFlag=2;
}
elseif(event->type()==QEvent::FocusOut)
{
QPalettep=QPalette();
p.setColor(QPalette::Base,Qt::white);
ui->secondLineEdit->setPalette(p);
printf("gettwofocusout\r\n");
m_editFlag=0;
}
}
returnQWidget::eventFilter(watched,event);
}


單個控制元件分別設定焦點為無焦點即可。

Qt::TabFocus0x1the widget accepts focus by tabbing.
Qt::ClickFocus0x2the widget accepts focus by clicking.
Qt::StrongFocusTabFocus | 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::WheelFocusStrongFocus | 0x4like Qt::StrongFocus plus the widget accepts focus by using the mouse wheel.
Qt::NoFocus0 the widget does not accept focus.

嘗試了所有的pushbotton一個介面禁用,但是失敗了。

在ui介面設定屬性中直接設定更方便。

選中控制元件,在右側屬性欄中找到QWidget->focusPolicy->選擇NoFocus,則此控制元件不產生焦點。