Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a static text (postfix, prefix) in QLineEdit?

How can I put a static text in QLineEdit in Qt C++ so that it can not be deleted and when I write to QLineEdit, it should not be spaced.

like image 238
Programming Avatar asked Feb 12 '23 10:02

Programming


1 Answers

There is no regular way to put a prefix or postfix in QLabel.

Placeholder

As far as you can get with QLineEdit is to set a text which will be displayed when there is no text indide - see QLineEdit::placeholderText.

enter image description here

InputMask

Another way to do it with QLineEdit is to set inputMask but it will change a cursor and will require a specific amount of letters.

enter image description here

Postfix with QLabel

If you know maximum amount of symbols and want to make a postfix, you can get it with another QLabel:
1. Limit length of the text to have a certain free space at right.
2. Place QLabel to the right side of the QLineEdit and enter a postfix text into it.

NOTE: you won't be able to put QLabel on QLineEdit in QtDesigner if the QLineEdit is inside of a layout. In this case you can add QWidget instead of QLineEdit in the layout and put QLineEdit and QLabel within this widget which doesn't have a layout. Also you can create QLabel in the code:

QLabel* label = new QLabel(this);
label->setText("kg");
label->move(lineEdit->rect().right() - label->width() - 3, lineEdit->rect().center().y() - label->height() / 2);

enter image description here

Custom Widget

Most flexible way to add a postfix and a prefix is to create a new class inherited from QWidget add two QLabels (prefix and postfix) info it, add QLineEdit between them and use css to make them look like a single QLineEdit.

enter image description here

On this image: Prefix and postfix are QLabels. _some_text_ is QLineEdit named lineEdit and all of them are inside a QWidget named complexLineEdit in a horizontal layout.

Here is a css I used for the image above:

QWidget#complexLineEdit
{
  border-top: 1px solid #CCCCCC;
  border-left: 1px solid #DDDDDD;
  border-right: 1px solid #DDDDDD;
  border-bottom: 1px solid #DDDDDD; 
  background-color: white;
}

QWidget#complexLineEdit QLineEdit#lineEdit
{
   border: 0px;
}

You can play with it to make it even more similar to QLineEdit.

like image 163
Ezee Avatar answered Feb 16 '23 04:02

Ezee