除了覆盖Esc
或使用事件过滤器/ reject()
方法之外,我可以阻止非模态QDialog在用户点击event
时关闭吗?
如果没有,是否可以使用模态QDialog?
答案 0 :(得分:1)
如果您不想使用eventFilter,可以使用QShortcut为Escape创建键盘快捷键并调用对话框的show slot。这可以这样做:
MyDialog::MyDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::MyDialog)
{
ui->setupUi(this);
QShortcut * shortcut = new QShortcut(QKeySequence(Qt::Key_Escape),this,SLOT(show()));
shortcut->setAutoRepeat(false);
}
答案 1 :(得分:0)
您可以在对话框中覆盖eventFilter,并在按下Escape时自行管理:
MyDialog::MyDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::MyDialog)
{
ui->setupUi(this);
this->installEventFilter(this);
}
bool MyDialog::eventFilter(QObject *obj, QEvent * event)
{
if((MyDialog *)obj == this && event->type()==QEvent::KeyPress && ((QKeyEvent*)event)->key() == Qt::Key_Escape )
{
return true;
}
return false;
}
答案 2 :(得分:0)
创建一个基于QObject的类来接收事件: -
class MyEvents : public QObject
{
Q_OBJECT
public:
MyEvents(QObject* parent);
protected:
bool eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if(keyEvent->key() == Qt::Key_Escape)
return true;
else
return QObject::eventFilter(obj, event);
}
else
{
// standard event processing
return QObject::eventFilter(obj, event);
}
}
};
然后将对象安装为对话框的事件过滤器
MyEvents* myEvents = new MyEvents;
QDialog myDialog(parent);
myDialog->installEventFilter(myEvents);