锁定按键:
#ifndef WIDGET_H
#define WIDGET_H
#include <QtGui/QWidget>
#include <QPushButton>
//-----------------------------------------------------
class TestOther :public QWidget
{
public:
TestOther(QWidget *parent = 0);
};
//-----------------------------------------------------
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
private slots:
void LockKey();
void showOther();
protected:
bool eventFilter(QObject *target, QEvent *event);
bool bLockKey;
QPushButton *ptnLock;
};
#endif // WIDGET_H
//--------------------------------------------------------
#include "widget.h"
#include <QMessageBox>
#include <QGridLayout>
#include <QLineEdit>
#include <QKeyEvent>
#include <QTextCodec>
#include <QApplication>
#include <QPushButton>
//原理就是利用事件过滤器来做的。第一步安装事件过滤器,第二步重载eventFilter函数。
//-------------------------------------------------------
TestOther::TestOther(QWidget *parent)
: QWidget(parent)
{
QGridLayout *gridWin=new QGridLayout;
QLineEdit *line1=new QLineEdit;
QLineEdit *line2=new QLineEdit;
gridWin->addWidget(line1,0,0);
gridWin->addWidget(line2,1,0);
setLayout(gridWin);
}
//-------------------------------------------------------
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
qApp->installEventFilter(this); //安装事件过滤器。qApp为应用程序的全局变量名
bLockKey=false;
QGridLayout *gridWin=new QGridLayout;
QLineEdit *line1=new QLineEdit;
QLineEdit *line2=new QLineEdit;
ptnLock=new QPushButton("Lock");
connect(ptnLock,SIGNAL(clicked()),this,SLOT(LockKey()));
QPushButton *ptnTest=new QPushButton("show other");
connect(ptnTest,SIGNAL(clicked()),this,SLOT(showOther()));
gridWin->addWidget(line1,0,0);
gridWin->addWidget(line2,1,0);
gridWin->addWidget(ptnLock,2,0);
gridWin->addWidget(ptnTest,3,0);
setLayout(gridWin);
}
Widget::~Widget()
{
}
bool Widget::eventFilter(QObject *target, QEvent *event)
{
if (event->type() == QEvent::KeyPress)
{
if(bLockKey!=true)
{
QWidget::eventFilter(target, event);//抛个父类
}
}
else
{
QWidget::eventFilter(target, event);//抛个父类
}
}
void Widget::LockKey()
{
if(ptnLock->text()=="Lock")
{
ptnLock->setText("Unlock");
bLockKey=true;
}
else
{
ptnLock->setText("Lock");
bLockKey=false;
}
}
void Widget::showOther()
{
TestOther *test=new TestOther;
test->show();
}