【问题标题】:Managing the escape key to quit a program管理退出键以退出程序
【发布时间】:2016-04-11 15:04:31
【问题描述】:

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

这是我的实际代码:

    #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_ */

【问题讨论】:

    标签: c++ qt events key keyevent


    【解决方案1】:

    您需要重写方法void QWidget::keyPressEvent(QKeyEvent *event)。对你来说它看起来像这样:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】: