понедельник, 22 июня 2009 г.

QLineEditGhost

Слепил себе простенький виджет на Qt 4.5.1. Строка ввода с "призрачной" надписью. Интересно почему изначально не присутствовала эта возможность у QLineEdit-а.


Рис. 1. Анимация (18Кб)

Исходник:

#ifndef QLINEEDITGHOST_H
#define QLINEEDITGHOST_H

#include <QLineEdit>

class QLineEditGhost : public QLineEdit
{
Q_OBJECT

bool isGhostNow;
QString ghostText_;
public:
QLineEditGhost ( const QString & str = "", QWidget * parent = NULL):
QLineEdit(parent), ghostText_(str), isGhostNow(true)
{
connect( this, SIGNAL(cursorPositionChanged(int,int)),
this, SLOT(cursorPositionChangedGhost(int,int)) );
connect( this, SIGNAL(textEdited(QString)),
this, SLOT(textEditedGhost(QString)) );
setText( ghostText() );
QPalette pal = palette();
pal.setColor( QPalette::Text, QColor(128,128,128) );
setPalette(pal);
}

QString text () const
{
if (isGhostNow)
return "";
return QLineEdit::text();
}

QString ghostText() const {
return ghostText_;
}
void setGhostText(const QString &ghostText_in) {
ghostText_ = ghostText_in;
}


public slots:
void cursorPositionChangedGhost(int from, int to)
{
if ((to != 0) && isGhostNow)
setCursorPosition(0);
}
void textEditedGhost(QString str)
{
QPalette pal = palette();
if (isGhostNow)
{
pal.setColor( QPalette::Text, QColor(0,0,0) );
setPalette(pal);
isGhostNow = false;
setText( text().left( text().length() - ghostText_.length() ) );
}
if (text().length() == 0)
{
pal.setColor( QPalette::Text, QColor(128,128,128) );
setPalette(pal);
isGhostNow = true;
setText( ghostText_ );
}
}

};

#endif // QLINEEDITGHOST_H

Подсветка синтаксиса выполнена при помощи Notepad++



Во время написания кода возникли проблемы в вызовом протектед метода
родительского класса. Пытался написать так: ((QLineEdit*)this)->text()
Думал-думал и придумал: QLineEdit::text()

Ну и в конце концов, меня уже взбесило, что исходник не влазит по ширине и по-уродски обрубаются строчки. Увеличил ширину блога на 200 пикселей. Теперь ширина 944px. Картинку-шапку тоже пришлось увеличить.

Комментариев нет: