How to set number of lines for an QTextEdit? - c++

I use a QTextEdit for some inputs. But I want to adjust the height of the box. Can I set the height based on the number of lines I want to have visible at a time?

If you use QPlainTextEdit, something like this should do the trick:
void SetHeight (QPlainTextEdit* edit, int nRows)
{
QFontMetrics m (edit -> font()) ;
int RowHeight = m.lineSpacing() ;
edit -> setFixedHeight (nRows * RowHeight) ;
}
You might want to add two or three pixels as margin; experiment will tell.

Improving the accepted answer about QPlainTextEdit. In addition to lineSpacing, value for setFixedHeight should contain: 2 margins of the underlying QTextDocument, 2 widths of the frame and widget's contents margins. Besides that, QFontMetrics must be got from a font of the document, not of the widget itself. So, hypothetical function setHeight should read as follows:
void setHeight (QPlainTextEdit *ptxt, int nRows)
{
QTextDocument *pdoc = ptxt->document ();
QFontMetrics fm (pdoc->defaultFont ());
QMargins margins = ptxt->contentsMargins ();
int nHeight = fm.lineSpacing () * nRows +
(pdoc->documentMargin () + ptxt->frameWidth ()) * 2 +
margins.top () + margins.bottom ();
ptxt->setFixedHeight (nHeight);
}

Use QFont to determine the height of a single line of text in the QTextEdit (QTextEdit should have a font property). After that multiply the QFont's height value with the number of lines you want to show and set the widget's (minimum-)height to that value.

QTextEdit is a normal widget, so you can use minimumHeight property. I believe, however, that it is really impossible to set minimum height based on number of lines. This would resize automagically the minimum size of a widget every time you change size of the font. But if you know the size of the font, you can set some usable minimum size of your widget.

This should work:
QTextEdit *myEdit = new QTextEdit(myContentString);
QSize myEditSize = myEdit->document()->size().toSize();
myEditSize.setWidth(QWIDGETSIZE_MAX);
myEdit->setMaximumSize(myEditSize);

Related

How to adjust QTextEdit to fit it's contents

I'm developing a Qt Application and I'm trying to find a way to use QTextEdit as a label with long text without the scroll bar. In my ui I have a QScrollArea and inside of it I want to place a couple off QTextEdit widgets and I only want use scrolling inside QScrollArea. Problem is that no matter how I try to resize the QTextEdit it seems it has a maximum height and cuts of text, even if I set the size manually and QTextEdit::size returns the correct value.
I did the same thing with QLabel and it works fine, but in this case I need some methods that are only provided in QTextEdit.
I found this post:
Resizing QT's QTextEdit to Match Text Height: maximumViewportSize()
And the answer given was the following:
I have solved this issue. There were 2 things that I had to do to get
it to work:
Walk up the widget hierarchy and make sure all the size policies made
sense to ensure that if any child widget wanted to be big/small, then
the parent widget would want to be the same thing.
This is the main
source of the fix. It turns out that since the QTextEdit is inside a
QFrame that is the main widget in a QScrollArea, the QScrollArea has a
constraint that it will not resize the internal widget unless the
"widgetResizable" property is true. The documentation for that is
here: http://doc.qt.io/qt-4.8/qscrollarea.html#widgetResizable-prop.
The documentation was not clear to me until I played around with this
setting and got it to work. From the docs, it seems that this property
only deals with times where the main scroll area wants to resize a
widget (i.e. from parent to child). It actually means that if the main
widget in the scroll area wants to ever resize (i.e. child to parent),
then this setting has to be set to true. So, the moral of the story is
that the QTextEdit code was correct in overriding sizeHint, but the
QScrollArea was ignoring the value returned from the main frame's
sizeHint.
The problem is that I have no idea how to access the QTextEdit's QScrollArea to enable widgetResizable. Can anyone explain how I can achieve this or suggest a different way of resizing QTextEdit to perfectly fit it's content?
This will allow the height of the text box to change as required. You can edit the code a little to handle the width as well.
connect( m_textField, SIGNAL( textChanged() ), this, SLOT( onTextChanged() ) );
void MyClass::onTextChanged()
{
QSize size = m_textField->document()->size().toSize();
m_textField->setFixedHeight( size.height() + 3 );
}
Try this one :
QTextEdit textEdit;
textEdit.setHtml("<p>test test test test test test</p><p>|||||||||</p>");
textEdit.show();
textEdit.setFixedWidth(textEdit.document()->idealWidth() +
textEdit.contentsMargins().left() +
textEdit.contentsMargins().right());
Without a concrete example it's difficult to judge, but... it sounds as if you simply want a QTextEdit whose sizeHint depends on the current document size.
class text_edit: public QTextEdit {
using super = QTextEdit;
public:
explicit text_edit (QWidget *parent = nullptr)
: super(parent)
{
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
virtual QSize sizeHint () const override
{
QSize s(document()->size().toSize());
/*
* Make sure width and height have `usable' values.
*/
s.rwidth() = std::max(100, s.width());
s.rheight() = std::max(100, s.height());
return(s);
}
protected:
virtual void resizeEvent (QResizeEvent *event) override
{
/*
* If the widget has been resized then the size hint will
* also have changed. Call updateGeometry to make sure
* any layouts are notified of the change.
*/
updateGeometry();
super::resizeEvent(event);
}
};
Then use as...
QScrollArea sa;
sa.setWidgetResizable(true);
text_edit te;
te.setPlainText(...);
sa.setWidget(&te);
sa.show();
It appears to work as expected in the few tests I've done.
In ui i defined QTextEdit *textEdit object. I write it as height scalable-content :
int count = 0;
QString str = "";
// set textEdit text
ui->textEdit->setText("hfdsf\ncsad\nfsc\dajkjkjkjhhkdkca\n925");
str = ui->textEdit->toPlainText();
for(int i = 0;i < str.length();i++)
if(str.at(i).cell() == '\n')
count++;
// resize textEdit (width and height)
ui->textEdit->resize(ui->textEdit->fontMetrics().width("this is the max-length line in qlabel")
, ui->textEdit->fontMetrics().height() * (count + 2));
Notice : this work if you change QTextEdit font face or size! just in height scalable (before every thing set your QTextEdit frameShape to BOX).
if you want do width scalable-content, you should do these steps :
read QTextEdit(textEdit object) text as line to line
calculate every line length
select maximum of line length
use of QTextEdit::fontMetrics().width(QString str) for investigate str size in width
I hope this can help you...

Calculate max length of QLineEdit to suit its width

I created some QLineEdit, which have different sizes.
I want to set the max length of those to suit the width of them.
To be more specific: for example, with a width of 50, I will only allow to enter about 7 characters, because the size of each character is different.
How can I exactly calculate the maximum length needed?
You can set a limit based on the width of myLineEdit such that it will be able to fit all characters up to that limit by doing this:
#include <QFontMetrics>
#include <QLineEdit>
QLineEdit myLineEdit;
// get max character width of the line edit's font
int maxWidth = QFontMetrics(myLineEdit->font()).maxWidth();
// find the character limit based on the max width
int charlimit = myLineEdit.width() / maxWidth;
// set the character limit on the line edit
myLineEdit->setMaxLength(charlimit);
However, here are some reasons you probably don't want to in production code:
Stylesheets - what happenes when your designer gives the edit a 14px border?
Resizing - you'll have to adjust this on every resize, and I've found that in practice it's a very difficult thing to keep track of. It's not a useful feature if it breaks whenever the GUI gets resized.
Content - the width of the line edit, especially one that a user can enter text into, is not logically related to the length of text the user may need to enter. This could become an arbitrary constraint that frustrates your users. No one likes horizontal scrolling, but sometimes there are use cases.
Use a QFontMetrics:
QFontMetrics fm(QApplication::font()); // You can use any font here.
int stringWidth = fm.width("Some string");
EDIT:
At first you have to know when your QLineEdit is resized. So you can either derive your own class and reimplement the resizeEvent() method, or you can use an event filter.
Then create a special validator:
class CLengthValidator : public QValidator
{
public:
CLenghtValidator(QObject* parent, const QFont & font)
: QValidator(parent), m_maxw(0), m_fm(font)
{}
void setMaxValidWidth(int width)
{
m_maxw = width;
}
State validate(QString & input, int & pos) const override
{
int stringWidth = m_fm.width(input);
if (stringWidth <= m_maxw)
return Acceptable;
else
return Invalid;
}
private:
int m_maxw;
QFontMetrics m_fm;
}
Set the validator to your line edit (using the QLineEdit::setValidator() method):
lineEdit->setValidator(new CLengthValidator(lineEdit, lineEdit->font()));
Now, every time the line edit is resized, you have to call CLengthValidator::setMaxValidWidth() method with the current line edit width as a parameter. You will do that in your reimplemented QLineEdit::resizeEvent() method or in your event filter.
This way you will get a line edit accepting only string which width is not greater than width of actual line edit.

Set slider size of QScrollBar correspond with content

I am doing a software with a drawing surface that represent a plot (like a sin function) (A child of QWidget) and I would like to have a QScrollBar acting like a QScrollArea. So if my drawing widget show show 750 dots (my plot is made of dots), but there are 1000 dots, I would like the slider of the ScrollBar to fill 75% of the available space.
I can't use a QScrollArea because the scroll is proportionnal with the size of the widget it contains. In my case, the scroll must be proportionnal with the number of dots on the screen. I know how to get my ratio, but I don't know how to setup correctly the QScrollBar
Example: I edited the value of PageStep, but I don't understand how this work. I can set pageStep to 100 with a range of [0,99] and it will fill the half of the QScrollBar.
My interface:
QWidget (Vertical Layout) //Main Widget
Drawing Surface (Child of QWidget)
QScrollBar (Horizontal)
Well, I think I am able to do something with this:
http://harmattan-dev.nokia.com/docs/library/html/qt4/qscrollbar.html
The relationship between a document length, the range of values used in a scroll bar, and the page step is simple in many common situations. The scroll bar's range of values is determined by subtracting a chosen page step from some value representing the length of the document. In such cases, the following equation is useful: document length = maximum() - minimum() + pageStep().
So in my case the length is the number of dots and I can set minimum() to 0. So, as you can see on the picture, to do something like QScrollArea. The proportion is: PercentageVisible = PageStep / Length and another equation is Length = PageStep + Max.
I have two equations, two missing values (PageStep and Maximum) and two known values (PercentageVisible and Length).
Example: I have 1024 dots, but only 75% of them are shown.
0.75 = PageStep / 1024 ----------> PageStep = 768
1024 = Max + 768 ----------------> Max = 256
You can try it in your software and it will works. I know there's not so much people that will needs to reproduce this because QScrollArea will do the job in most of the case.
By example, this code is in a slot reacting from a resize event:
ui.sbarRange->setPageStep(u64SampleCount * dRatio);
ui.sbarRange->setMaximum(u64SampleCount - ui.sbarRange->pageStep());
You can create a new QWidget subclass and reimplement sizeHint and paintEvent. In the paintEvent you can use event->rect() to determine which area is currently exposed and needs to be drawn. Note that paintEvent must be fast if you don't want your window to freeze. Also you need to put created widget in QScrollArea.
Here is a simple example that draws a sinusoid:
class SinWidget : public QWidget {
public:
QSize sizeHint() const {
return QSize(10000, 200);
}
void paintEvent(QPaintEvent* event) {
QPainter painter(this);
for(int x = event->rect().left(); x <= event->rect().right(); x++) {
painter.drawPoint(x, 100.0 + qSin(0.05 * x) * 20.0);
}
}
};
QScrollArea area;
area.setWidget(new SinWidget());
area.show();
This example will work fine with very large widget size (e.g. 100 000 pixels). So full repaint or memory allocation doesn't happen. You only need to keep your paintEvent fast.

Qt: heightForWidth for word-wrapped text

I have a box with a varying width and a word-wrapped text. I need to set new height every time user changes box's width. The box is displayed by QPainter inside paintEvent(QPaintEvent *) function. There is several solutions, for example current (not very smart, i do this in resizeEvent(QResizeEvent *)):
unsigned new_height = 0; // the height i want to find out.
unsigned given_width = width();
QPainter painter (this); // i need painter, because i want to ask it's default font.
QLabel lab; // the widget that can do word-wrap.
lab.setText( "A word wrapped text" ); // the text
lab.setFont( painter.font() ); // set QPainter's default font.
lab.setWordWrap( true ); // enable word-wrap
new_height = lab.heightForWidth( given_width ); // tada! :)
But the code is overkill:
1) Creading QPainter is not good outside paintEvent(QPaintEvent *);
2) BUT i need QPainter to request what font is default for it to ask metrics for that font.
Should i change my code and do this operation with help of QPainter::boundingRect() inside the paintEvent(QPaintEvent *) function? But i'd like to reduce CPU consumption inside the paintEvent(QPaintEvent *) and calculate new height only when width changed, but not every time it displayed.
What is other solutions for the purpose of subject? QFontMectircs?
I think you have the right idea of using QFontMetrics. The whole idea of the class is to assist the situations like you have here. Take a look at QFontMetricsF::boundingRect()
Use your target paint rectangle as the input rect, but set the height to the max that your widget height. I'd just put something like INT_MAX in it just to be sure. :)

Qt - How to specify and make constant an element size in a layout?

Say there is a QHBoxLayout and some widgets in it. How to specify a widget width and hight in the layout, so that while resizing the widget which containes the layout the given width and hight stay constant?
You can use
void QWidget::setFixedSize ( int w, int h )
which Sets the width of the widget to w and the height to h. This will make the size of the particular widget fixed when the window is re-sized.
Also you can use the combination of these functions,
void QWidget::setFixedHeight ( int h )
and also
void QWidget::setFixedWidth ( int w )
whichever is required for your need.. Hope it helps.
One (simple) way to do this is to use QWidget::setMinimumSize and QWidget::setMaximumSize functions to set minimum size and maximum size to be the same. Doing this will prevent widget from expanding and shrinking. E.g.
widget->setMinimumSize( 200, 100 );
widget->setMaximumSize( 200, 100 );
Of course you can set these values in QtDesigner also.