Russian Qt Forum
Май 29, 2024, 09:00 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
  Начало   Форум  WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  

Страниц: [1]   Вниз
  Печать  
Автор Тема: QLineEdit и Enter(Return)  (Прочитано 7953 раз)
anv
Гость
« : Сентябрь 14, 2012, 16:21 »

Привет.Есть два класса- MyLineEdit(QLineEdit) и MyPixmapItem(QObject,QGraphicsPixmapItem). Когда вводится правильное имя ,при нажатии кнопки V картинка меняется.Если неправильное- очистка LineEdit. Через событие KeyPressEvent. Все работает,но с Enter или Return вместо V - не хочет.Пробовал returnPressed - то же не работает. Как бы заставить это работать с намлуковским Enter ом.
Код:
#ifndef _MyLineEdit_h_
#define _MyLineEdit_h_

#include <QtGui/QtGui>
#include <QtCore/QtCore>
#include "MyPixmapItem.h"
//class MyPixmapItem;

class MyLineEdit : public QLineEdit
{
Q_OBJECT

public:
    MyLineEdit(QWidget*pwgt,MyPixmapItem*myp);

public slots:
//void connector_qstring();
   
protected:
    virtual void keyPressEvent(QKeyEvent*pe);
   virtual void keyReleaseEvent(QKeyEvent*re);

private:

MyPixmapItem*mypix;
};
#endif //_MyLineEdit_h_
/////////////////////////////////////////////////////////////////////////////////////////
#include "MyLineEdit.h"

MyLineEdit::MyLineEdit(QWidget*pwgt,MyPixmapItem*myp): QLineEdit(pwgt),mypix(myp)
{
//connect(this,SIGNAL(returnPressed()),this,SLOT(connector_qstring()));

}



//void MyLineEdit::connector_qstring()
//{connect(this, SIGNAL(textChanged(const QString&)),
// mypix, SLOT(change_picture(const QString&)));
//connect(mypix, SIGNAL(clear_lineedit()),
// this, SLOT(clear()));
//}


void MyLineEdit::keyPressEvent(QKeyEvent*pe)
{if (pe->key() == Qt::Key_V){connect(this,SIGNAL(textChanged(const QString&)),
mypix, SLOT(change_picture(const QString&)));
connect(mypix, SIGNAL(clear_lineedit()),
this, SLOT(clear()));


}
   QLineEdit::keyPressEvent(pe);
}

void MyLineEdit:: keyReleaseEvent(QKeyEvent*re)
{if (re->key() == Qt::Key_V){disconnect(this, SIGNAL(textChanged(const QString&)),
mypix, SLOT(change_picture(const QString&)));
disconnect(mypix, SIGNAL(clear_lineedit()),
this, SLOT(clear()));
}
  QLineEdit::keyReleaseEvent(re);
}
///////////////////////////////////////////////////////////////////////////////////
#include <QtGui/QtGui>
#include <QtCore/QtCore>
//#include "MyLineEdit.h"

class MyPixmapItem : public QObject, public QGraphicsPixmapItem
{
Q_OBJECT
   
public:
      MyPixmapItem(QPixmap& pix,QObject*parent,QGraphicsItem*par);
     void temp(bool&typ);
public slots:
  void change_picture(const QString& npic);

    signals:
  void clear_lineedit();



   

    private:
  QPixmap pixmap;
  QString name;
  bool typetemp;

};
#endif //_MyPixmapItem_h_
/////////////////////////////////////////////////////////////
#include "MyPixmapItem.h"

MyPixmapItem::MyPixmapItem(QPixmap& pix,QObject*parent,QGraphicsItem*par):QObject(parent),QGraphicsPixmapItem(pix,par)
{}

void MyPixmapItem::change_picture(const QString&npic)
{   QString puth="images/";
    QString p_type=".jpg";
QString f_name;
QString n_name;
//setText(npic);
n_name=npic;
    f_name=puth+n_name+p_type;
////////////
    QPixmap temppix;
if(temppix.load(f_name))
{setPixmap(temppix);}
else
{emit clear_lineedit();}
//setPixmap(QPixmap(f_name));

}

void MyPixmapItem:: temp(bool&typ)
{typ=isWidgetType();}
Записан
Serr500
Гость
« Ответ #1 : Сентябрь 14, 2012, 16:46 »

Qt::KeyboardModifiers QKeyEvent::modifiers() const
Qt::KeypadModifier - A keypad button is pressed.

int QKeyEvent::key() const
Qt::Key_Return
Qt::Key_Enter - Typically located on the keypad.
Записан
anv
Гость
« Ответ #2 : Сентябрь 14, 2012, 18:44 »

С любым Enter не хочет ...
Записан
anv
Гость
« Ответ #3 : Сентябрь 14, 2012, 20:38 »

Чего то вообще не пойму.Подцепил QMessageBox и text()на нажатие любой клавиши. Enter как и Shift выдает пустоту. Но для шифта есть
modifiers и ShiftModifier. А для Enter ничего не нашел. Может это вин7 так работает с Qt?
Записан
kambala
Джедай : наставник для всех
*******
Offline Offline

Сообщений: 4732



Просмотр профиля WWW
« Ответ #4 : Сентябрь 14, 2012, 21:59 »

cкорее всего какой-то другой элемент интерфейса перехватывает энтер раньше
Записан

Изучением C++ вымощена дорога в Qt.

UTF-8 has been around since 1993 and Unicode 2.0 since 1996; if you have created any 8-bit character content since 1996 in anything other than UTF-8, then I hate you. © Matt Gallagher
anv
Гость
« Ответ #5 : Сентябрь 15, 2012, 11:33 »

Простой пример QLabel и QLineEdit. Все таки Enter срабатывает ,но с задержкой .Ппосле ввода техта жмется энтер и только после нажатия какой либо еще текстовой клавиши текст передается в QLabel. Если же установленна буквенная клавиша,то текст отправляется сразу по нажатию.

Код:
#include <QtGui/QtGui>
#include <QtCore/QtCore>
#include "MyLineEdit.h"
#pragma comment(lib, "QtGui4.lib")
#pragma comment(lib, "QtCore4.lib")

// ----------------------------------------------------------------------
int main(int argc, char** argv)
{
    QApplication  app(argc, argv);
    QWidget        wgt;
    QLabel*    plblAge = new QLabel("Age");
    MyLineEdit*txtp =new MyLineEdit(&wgt,plblAge);

    QVBoxLayout* pvbxLayout = new QVBoxLayout;
    pvbxLayout->addWidget(plblAge);
    pvbxLayout->addWidget(txtp);

    wgt.setLayout(pvbxLayout);
    wgt.show();
    return app.exec();



}

/////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef _MyLineEdit_h_
#define _MyLineEdit_h_

#include <QtGui/QtGui>
#include <QtCore/QtCore>

class MyLineEdit : public QLineEdit
{

public:
    MyLineEdit(QWidget*pwgt,QLabel*lab);

void set_startconnect(int&st);

protected:
    virtual void keyPressEvent(QKeyEvent*pe);

private:

QLabel*label;

};
#endif //_MyLineEdit_h_
///////////////////////////////////////////////////////////////////////////////
#include "MyLineEdit.h"

MyLineEdit::MyLineEdit(QWidget*pwgt,QLabel*lab): QLineEdit(pwgt),label(lab)
{}



void MyLineEdit::keyPressEvent(QKeyEvent*pe)
{if (pe->key()==Qt::Key_Enter){//QMessageBox::information(0,"text",pe->text());
connect(this, SIGNAL(textChanged(const QString&)),
label, SLOT(setText(const QString&)));}
   //pe->ignore();
   QLineEdit::keyPressEvent(pe);
}
Записан
Bepec
Гость
« Ответ #6 : Сентябрь 15, 2012, 13:37 »

Эт у вас в коде прописано Улыбающийся Что если нажать ентер, то ПОСЛЕ соединить сигнал/слоты Улыбающийся
Записан
anv
Гость
« Ответ #7 : Сентябрь 15, 2012, 18:29 »

Спасибо.Вот я торможу...Сигнал ведь CHANGED!!! Улыбающийся
Записан
Страниц: [1]   Вверх
  Печать  
 
Перейти в:  


Страница сгенерирована за 0.151 секунд. Запросов: 22.