Обработчик Qt keyPressEvent реагирует только при нажатии клавиш Ctrl, Alt или Shift. - PullRequest
0 голосов
/ 24 июня 2018

Я пытался получить любую клавишу, используя функцию keyPressEvent () , но в режиме отладки я обнаружил, что эта функция вызывается только тогда, когда клавиша " shift / alt / ctrl " нажата. Я пытался нажать клавишу в textEdit поле.

tipmanager.h:

namespace Ui {
class TipManager;
}

class TipManager : public QWidget
{
    Q_OBJECT

public:
    explicit TipManager(QWidget *parent = 0);
    ~TipManager();

    ...

protected:
    virtual void keyPressEvent(QKeyEvent*);

    ...

private:
    void on_titleEdit_textChanged(const QString &title);
    void on_codeTextEdit_textChanged();
    void on_memoTextEdit_textChanged();
    void enableButtons();
    ...
private:
    Ui::TipManager *ui;
    ...
    QDirModel *model;

};

#endif // TIPMANAGER_H

tipmanager.cpp:

#include "tipmanager.h"
#include "ui_tipmanager.h"

TipManager::TipManager(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TipManager)
{
    ui->setupUi(this);

    ui->dirEdit->setReadOnly(true);

    ...
}

...

void TipManager::enableButtons()
{
    //disable new button when all text boxes are empty
    flagTitleEdit|flagCodeTextEdit|flagMemoTextEdit
            ? ui->newButton->setEnabled(true)
            : ui->newButton->setEnabled(false);
    //enable save button when only both title and codeText bit are true
    flagTitleEdit&flagCodeTextEdit
            ? ui->saveButton->setEnabled(true)
            : ui->saveButton->setEnabled(false);
    //enable edit button when even a single text box is not empty
    flagTitleEdit|flagCodeTextEdit|flagMemoTextEdit
            ? ui->editButton->setEnabled(true)
            : ui->editButton->setEnabled(false);
}

void TipManager::on_titleEdit_textChanged(const QString &title)
{
    //when title text is empty, title bit is false
    QString text = title;
    text.trimmed().isEmpty() ? flagTitleEdit = false
                   : flagTitleEdit = true;
    //memo title edit is modified
    flagModified = true;

    enableButtons();
}

void TipManager::on_codeTextEdit_textChanged()
{
    //when code text is empty, codeText bit is false
    QString text = ui->codeTextEdit->toPlainText();
    text.trimmed().isEmpty() ? flagCodeTextEdit = false
                    : flagCodeTextEdit = true;
    //code text edit is modified
    flagModified = true;

    enableButtons();
}

void TipManager::on_memoTextEdit_textChanged()
{
    //when memo text is empty, memoText bit is false
    QString text = ui->memoTextEdit->toPlainText();
    text.trimmed().isEmpty() ? flagMemoTextEdit = false
                    : flagMemoTextEdit = true;
    //memo text edit is modified
    flagModified = true;

    enableButtons();
}

void TipManager::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_Tab)
    {

    }

}

tipmanager.ui:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>TipManager</class>
 <widget class="QWidget" name="TipManager">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>900</width>
    <height>558</height>
   </rect>
  </property>
  <property name="sizePolicy">
   <sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred">
    <horstretch>0</horstretch>
    <verstretch>0</verstretch>
   </sizepolicy>
  </property>
  <property name="minimumSize">
   <size>
    <width>720</width>
    <height>0</height>
   </size>
  </property>
  <property name="windowTitle">
   <string>TipManager</string>
  </property>
  <layout class="QGridLayout" name="gridLayout">
   <item row="0" column="1">
    <widget class="Line" name="line">
     <property name="enabled">
      <bool>true</bool>
     </property>
     <property name="orientation">
      <enum>Qt::Vertical</enum>
     </property>
    </widget>
   </item>
   <item row="0" column="2">
    <widget class="QWidget" name="RightLayout" native="true">
     <property name="sizePolicy">
      <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
       <horstretch>0</horstretch>
       <verstretch>0</verstretch>
      </sizepolicy>
     </property>
     <layout class="QVBoxLayout" name="rightLayout">
      <property name="spacing">
       <number>10</number>
      </property>
      <property name="sizeConstraint">
       <enum>QLayout::SetMinimumSize</enum>
      </property>
      <property name="leftMargin">
       <number>1</number>
      </property>
      <item>
       <layout class="QVBoxLayout" name="verticalLayout_3">
        <item>
         <widget class="QLabel" name="label_memo">
          <property name="text">
           <string>Memo</string>
          </property>
         </widget>
        </item>
        <item>
         <widget class="QTextEdit" name="memoTextEdit">
          <property name="enabled">
           <bool>true</bool>
          </property>
          <property name="minimumSize">
           <size>
            <width>0</width>
            <height>0</height>
           </size>
          </property>
          <property name="cursor" stdset="0">
           <cursorShape>IBeamCursor</cursorShape>
          </property>
         </widget>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QVBoxLayout" name="verticalLayout_2">
        <item>
         <layout class="QHBoxLayout" name="horizontalLayout_3">
          <item>
           <widget class="QLabel" name="label_file">
            <property name="text">
             <string>File</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QLineEdit" name="dirEdit">
            <property name="minimumSize">
             <size>
              <width>0</width>
              <height>0</height>
             </size>
            </property>
            <property name="cursor">
             <cursorShape>ArrowCursor</cursorShape>
            </property>
            <property name="mouseTracking">
             <bool>false</bool>
            </property>
            <property name="acceptDrops">
             <bool>false</bool>
            </property>
           </widget>
          </item>
         </layout>
        </item>
        <item>
         <widget class="QTreeView" name="treeView">
          <property name="minimumSize">
           <size>
            <width>0</width>
            <height>0</height>
           </size>
          </property>
          <property name="cursor" stdset="0">
           <cursorShape>ArrowCursor</cursorShape>
          </property>
         </widget>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QVBoxLayout" name="verticalLayout">
        <item>
         <layout class="QHBoxLayout" name="horizontalLayout">
          <item>
           <widget class="QPushButton" name="newButton">
            <property name="enabled">
             <bool>false</bool>
            </property>
            <property name="text">
             <string>New</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QPushButton" name="editButton">
            <property name="enabled">
             <bool>false</bool>
            </property>
            <property name="text">
             <string>Edit</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QPushButton" name="searchButton">
            <property name="text">
             <string>Search</string>
            </property>
           </widget>
          </item>
         </layout>
        </item>
        <item>
         <layout class="QHBoxLayout" name="horizontalLayout_2">
          <item>
           <widget class="QPushButton" name="loadButton">
            <property name="text">
             <string>Load Dir</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QPushButton" name="saveButton">
            <property name="enabled">
             <bool>false</bool>
            </property>
            <property name="text">
             <string>Save</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QPushButton" name="aboutButton">
            <property name="enabled">
             <bool>false</bool>
            </property>
            <property name="text">
             <string>About</string>
            </property>
           </widget>
          </item>
         </layout>
        </item>
       </layout>
      </item>
     </layout>
    </widget>
   </item>
   <item row="0" column="0">
    <widget class="QWidget" name="LeftLayout" native="true">
     <property name="sizePolicy">
      <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
       <horstretch>0</horstretch>
       <verstretch>0</verstretch>
      </sizepolicy>
     </property>
     <property name="minimumSize">
      <size>
       <width>550</width>
       <height>480</height>
      </size>
     </property>
     <layout class="QVBoxLayout" name="leftLayout">
      <property name="spacing">
       <number>10</number>
      </property>
      <property name="sizeConstraint">
       <enum>QLayout::SetMinAndMaxSize</enum>
      </property>
      <property name="leftMargin">
       <number>1</number>
      </property>
      <property name="rightMargin">
       <number>1</number>
      </property>
      <item>
       <layout class="QVBoxLayout" name="verticalLayout_4">
        <item>
         <widget class="QLabel" name="label">
          <property name="text">
           <string>Title</string>
          </property>
         </widget>
        </item>
        <item>
         <widget class="QLineEdit" name="titleEdit">
          <property name="enabled">
           <bool>true</bool>
          </property>
          <property name="minimumSize">
           <size>
            <width>0</width>
            <height>0</height>
           </size>
          </property>
         </widget>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QVBoxLayout" name="verticalLayout_5">
        <item>
         <widget class="QLabel" name="label_code">
          <property name="text">
           <string>Code</string>
          </property>
         </widget>
        </item>
        <item>
         <widget class="QTextEdit" name="codeTextEdit">
          <property name="enabled">
           <bool>true</bool>
          </property>
          <property name="minimumSize">
           <size>
            <width>0</width>
            <height>0</height>
           </size>
          </property>
          <property name="cursor" stdset="0">
           <cursorShape>IBeamCursor</cursorShape>
          </property>
         </widget>
        </item>
       </layout>
      </item>
     </layout>
    </widget>
   </item>
  </layout>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

Я, конечно, объявил #include <QKeyEvent>, а также написал setFocusPolicy(), но это не помогло. Я использую интерфейс с диалогом, поэтому не в случае MainWindows. Я хочу знать, почему это обнаруживает только ключ shift / alt / ctrl . Я использую Qt 5.3.

1 Ответ

0 голосов
/ 25 июня 2018

Если вы хотите захватить ключи при нажатии на codeTextEdit, вы должны реализовать фильтр событий, как показано ниже:

tipmanager.h

#ifndef TIPMANAGER_H
#define TIPMANAGER_H

#include <QWidget>

namespace Ui {
class TipManager;
}

class TipManager : public QWidget
{
    Q_OBJECT

public:
    explicit TipManager(QWidget *parent = 0);
    ~TipManager();

    bool eventFilter(QObject *watched, QEvent *event);

private:
    Ui::TipManager *ui;
};

#endif // TIPMANAGER_H

tipmanager.cpp

#include "tipmanager.h"
#include "ui_tipmanager.h"

#include <QKeyEvent>
#include <QTextEdit>

#include <QDebug>

TipManager::TipManager(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TipManager)
{
    ui->setupUi(this);
    ui->codeTextEdit->installEventFilter(this);
}

TipManager::~TipManager()
{
    delete ui;
}

bool TipManager::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->codeTextEdit && event->type() == QEvent::KeyPress){
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        qDebug()<<keyEvent->key();
    }
    return QWidget::eventFilter(watched, event);
}
...