管理转义键以退出程序

时间:2016-04-11 15:04:31

标签: c++ qt events key keyevent

我不知道如何实现管理退出键以退出程序。我不知道在我的代码中把它放在哪里,因为如果我把它放在一个方法中,它怎么能在任何地方退出?

这是我的实际代码:

    #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 个答案:

答案 0 :(得分:6)

您需要覆盖方法void QWidget::keyPressEvent(QKeyEvent *event)。它看起来像这样:

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

答案 1 :(得分:0)

我知道您已经解决了这个问题,而我的解决方案是使用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)

很显然,删除第一行后,可以将此代码添加到类构造函数中。