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.
There is no regular way to put a prefix or postfix in QLabel.
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.

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.

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);

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.

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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With