管理"ESC"键以退出程序

5

我不知道如何实现使用Esc键退出程序的管理。我也不知道在我的代码中应该把它放在哪里,因为如果我把它放在一个方法中,那么它怎么能够随时退出呢?

这是我的实际代码:

    #include <iostream>
    #include <QApplication>
    #include <QPushButton>
    #include <QLineEdit>
    #include <QFormLayout>
    #include <QDebug>
    #include "LibQt.hpp"

    LibQt::LibQt() : QWidget()
    {
      this->size_x = 500;
      this->size_y = 500;
      QWidget::setWindowTitle("The Plazza");
      setFixedSize(this->size_x, this->size_y);
      manageOrder();
    }

    LibQt::~LibQt()
    {
    }
void LibQt::manageOrder()
{
  this->testline = new QLineEdit;
  this->m_button = new QPushButton("Send Order");
  QFormLayout *converLayout = new QFormLayout;

  this->m_button->setCursor(Qt::PointingHandCursor);
  this->m_button->setFont(QFont("Comic Sans MS", 14));
  converLayout->addRow("Order : ", this->testline);
  converLayout->addWidget(this->m_button);
  this->setLayout(converLayout);
  QObject::connect(m_button, SIGNAL(clicked()), this, SLOT(ClearAndGetTxt()));
}

std::string     LibQt::ClearAndGetTxt()
{
  QString txt = this->testline->text();

  this->usertxt = txt.toStdString();
  std::cout << this->usertxt << std::endl;
  this->testline->clear();
  return (this->usertxt);
}

std::string     LibQt::getUsertxt()
{
  return (this->usertxt);
}

这是我的.hpp文件。

#ifndef _LIBQT_HPP_
#define _LIBQT_HPP_

#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QKeyEvent>
#include <QCheckBox>
#include <QPlainTextEdit>

class   LibQt : public QWidget
{
  Q_OBJECT

public:
  LibQt();
  ~LibQt();
  void manageOrder();
  std::string getUsertxt();
public slots:
  std::string ClearAndGetTxt();
protected:
  int   size_x;
  int   size_y;
  QPushButton *m_button;
  QLineEdit *testline;
  std::string usertxt;
};

#endif /* _LIBQT_HPP_ */
2个回答

7

您需要覆盖方法void QWidget::keyPressEvent(QKeyEvent *event)。对于您来说,它将如下所示:

void LibQt::keyPressEvent(QKeyEvent* event)
{
    if(event->key() == Qt::Key_Escape)
    {
         QCoreApplication::quit();   
    }
    else
        QWidget::keyPressEvent(event)
}

3

我知道你解决了这个问题,我的解决方案是用Python实现的,但其他人可能会发现这很有用。本质上,您可以将此功能实现为一个操作:

w = LibQt() # QWidget().

escape = QAction('Escape', w)
escape.setShortcut(QKeySequence('Esc'))
escape.setShortcutContext(Qt.WidgetWithChildrenShortcut) # acts as an event filter.
escape.triggered.connect(w.close)

w.addAction(escape)

显而易见,删除第一行后,这段代码可以添加到类构造函数中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接