Qt: How to force a hidden widget to calculate its layout? - c++

What I am trying to do is render a qwidget onto a different window (manually using a QPainter)
I have a QWidget (w) with a layout and a bunch of child controls. w is hidden. Until w is shown, there is no layout calculations happening, which is expected.
When I call w->render(painter, w->mapToGlobal(QPoint(0,0)), I get a bunch of controls all overlapping each other.
w->layout()->activate();w->layout()->update() doesn't seem to do anything.
Is there a way to force the layout to happen without showing w?

Forcing a layout calculation on a widget without showing it on the screen:
widget->setAttribute(Qt::WA_DontShowOnScreen);
widget->show();
The show() call will force the layout calculation, and Qt::WA_DontShowOnScreen ensures that the widget is not explicitly shown.

The layout calculation of a widget can be forced by calling invalidate() followed by activate() on its layout, even if the widget is hidden. This also causes the widget's size() and sizeHint() functions to return correct and updated values, even if show() has not yet been called on that widget.
It is however necessary to care about all child widgets and layouts recursively, as a layout recalculation request doesn't automatically propagate to the childs.
The following code shows how to do this.
/**
* Forces the given widget to update, even if it's hidden.
*/
void forceUpdate(QWidget *widget) {
// Update all child widgets.
for (int i = 0; i < widget->children().size(); i++) {
QObject *child = widget->children()[i];
if (child->isWidgetType()) {
forceUpdate((QWidget *)child);
}
}
// Invalidate the layout of the widget.
if (widget->layout()) {
invalidateLayout(widget->layout());
}
}
/**
* Helper function for forceUpdate(). Not self-sufficient!
*/
void invalidateLayout(QLayout *layout) {
// Recompute the given layout and all its child layouts.
for (int i = 0; i < layout->count(); i++) {
QLayoutItem *item = layout->itemAt(i);
if (item->layout()) {
invalidateLayout(item->layout());
} else {
item->invalidate();
}
}
layout->invalidate();
layout->activate();
}

Try with the QWidget::sizeHint() method, which is supposed to return the size of the widget once laid out.

I had some succes in a similar problem by first calling w->layout()->update() before w->layout()->activate(). That seems to force the activate() to actually do something rather than think it is fine because the window isn't being shown anyway.

When going through QWidget::grab() I noticed this part:
if (r.width() < 0 || r.height() < 0) {
// For grabbing widgets that haven't been shown yet,
// we trigger the layouting mechanism to determine the widget's size.
r = d->prepareToRender(QRegion(), renderFlags).boundingRect();
r.setTopLeft(rectangle.topLeft());
}
QWidget::grab() has been introduced in Qt 5.0, and this test function with a QDialog containing a layout seems to work on Qt 5.5.1
int layoutTest_2(QApplication& a)
{
CLayoutTestDlg dlg; // initial dlg size can also be set in the constructor
// https://stackoverflow.com/questions/21635427
QPixmap pixmap = dlg.grab(); // must be called with default/negative-size QRect
bool savedOK = pixmap.save("E:/temp/dlg_img.png");
// saving is not necessary, but by now the layout should be done
dlg.show();
return a.exec();
}

This worked for me when using the sizeHint() plus translating the painter, however I do this inside the paint() method.
void ParentWidget::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
painter->save();
painter->translate(option.rect.topLeft());
w->render(painter);
painter->restore();
}
In this case, option.rect.topLeft() gives me the correct placement. You should try a more sensible coordinate instead of w->mapToGlobal(QPoint(0,0).

Related

Move layout to another layout in Qt5

I have a custom container widget in Qt5 which has a QFrame without a layout. I use setLayout on QFrame which works fine but sometimes I want to transfer an existing layout which contains widgets and other layouts to that QFrame as layout. Is that even possible in Qt5 to transfer layouts already added with addLayout?
No problem. Just make the layout the layout of the target widget with setLayout(). The widgets contained will be reparented automatically.
void MainWindow::moveLayout()
{
// Move the layout from ui->g0 to ui->g1 and vice versa
// every time you call moveLayout
static int toggle = 0;
QLayout* l;
QWidget* w;
if (toggle == 0)
{
l = ui->g0->layout();
w = ui->g1;
}
else
{
l = ui->g1->layout();
w = ui->g0;
}
if (w->layout())
{
// Hack to clean target widget
QWidget z;
z.setLayout(w->layout());
}
w->setLayout(l);
toggle = 1 - toggle;
}

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...

Qt Scaling Custom QGraphicsItem with unscaled text

I'm trying to create customObject (rectangle and it inherit from QGraphicsItem) that will be painted on scene with ceratin text(stored in attribute), but when I scale it - i wish to keep same size of text. Here is my over. paint function:
void CustomRectangle::paint(QPainter *painter, const QStyleOptionGraphicsItem *options, QWidget *widget)
{
QColor currentColor = get_ColorByCurrentState();
QRectF rect = boundingRect();
QPen pen(currentColor, Own_LineWidith);
painter->setPen(pen);
painter->drawRect(rect);
QRectF rect_text(rect.x(), rect.y(),100,100);
painter->drawText(rect_text,this->getText() );
}
and my two scaling functions:
void CustomObject::scaleUp()
{
scale(ScaleFactor_X,ScaleFactor_Y);
}
void CustomObject::scaleDown()
{
scale(1/ScaleFactor_X,1/ScaleFactor_Y);
}
But text still keep scaling along with rectangle.
EDIT 1
I tried adding it another way, i nfucntion that creates and adds my rectangle to scene (here - named "newObject"), but result is still the same.
QGraphicsTextItem* GTI = new QGraphicsTextItem(newObject->toStringForScene(), newObject);
I'm beginign to think that I shoud create each text object as separeted object and save it different list. Ofcours, i would have to update it then, whenever it's object moved.
Try this:
QGraphicsTextItem* gti = new QgraphicsTextItem("text");
gti->setFont(QFont("Arial", 18));
// this is important
gti->setFlag(QGraphicsTextItem::ItemIgnoresTransformations, true);
scene->addItem(gti);
The QGraphicsItem::ItemIgnoresTransformations flag prevents your graphics item to be scaled when you scale your view (QGraphicsView).
That means that you need a separated item for rendering text. But it can be a child item of your rectangle item.
I resolved this with QGraphicsTextItem's poitner as class's attribute.
QGraphicsTextItem* GTI;
I initialzie it in constructor:
GTI_Description = new QGraphicsTextItem(this->toStringForScene());
and then I call function to updated it's X and Y:
void updateTextPosition()
{
GTI->setX( this->x() );
GTI->setY( this->y() );
}
and to add it to the scene:
addTextToScene(DragScene* _scene)
{
updateDescriptionPosition();
_scene->addItem(GTI_GTI);
_scene->update();
}
Then i just call updateTextPosition() whenerver I change positions (in my mouseRelease event's handler).

QT QGraphicsView rotation

Disclaimer: I am pretty much a beginner with QT.
I've been struggling for some time to rotate a QGraphicsView (no 3D rotation) but, despite what i do, it doesn't work. I have tried:
QTransform transform;
transform.rotate(45);
ui->graphicsView->setTransform(transform);
or more simply:
ui->graphicsView->rotate(45);
These seem like very straightforward ways to do it that should work, but for some reason, whenever i run it, the QGraphicsView doesn't rotate at all. If possible, i'd like some direct and easy to understand code snippets, and/or what i'm doing wrong.
EDIT: This is the code in the widget cpp file i have problems with. It should be a simple timer with an animated hourglass icon. It gets repeated every .5 seconds.
void Widget::timerEvent(QTimerEvent *event)
{
++timeFlag;
++timerFlag;
if (timerFlag < 115){
animateTimer = QString("\":/new/100/timerFrames/timerIconFrame%1.png\"").arg(timerFlag);
QPixmap pix(animateTimer);
pixmapitem.setPixmap(pix);
scene.addItem(&pixmapitem);
ui->graphicsView_2->setScene(&scene);
}
if (timerFlag >= 115 && timerFlag < 119){
//
}
if(timerFlag == 119){
ui->graphicsView_2->setStyleSheet("border-image:url(:/new/100/timerIconPix.PNG);border:0px;}");
}
if(timerFlag == 120){
timerFlag = 0;
}
if (timeFlag==2){
timeFlag = 0;
if(sec>=10){
ui->label_2->setText(QString("%1:%2").arg(min).arg(sec));
} else {
ui->label_2->setText(QString("%1:0%2").arg(min).arg(sec));
}
++sec;
if (sec == 60) {
sec = 0;
++min;
}
}
}
You're merely decorating the QGraphicsView using the style mechanism. You could have used a plain QWidget instead, since you don't use any graphics view functionality. None of the images in the stylesheet are what the view actually displays. The image must be on the scene displayed by the view.
Set the image on a QGraphicsPixmapItem, add that item to a scene, set the scene on the view, and then the transformations will work. You can then keep replacing the pixmap in the timer handler.
Finally, you must also check the timer id in the timerEvent. I assume that you're using a QBasicTimer, say called m_timer, you'd then check as follows:
void Widget::timerEvent(QTimerEvent * ev) {
if (ev->timerId() != m_timer.timerId()) return;
... // rest of the code
}
As you can see, the code that you've not included in the original question was absolutely essential! Without it, the question was wholly off-topic.
You need to implement a QGraphicsView, a QGraphicsScene and then add something that inherits from QGraphicsItem to that scene to rotate.
Here is an example that rotates a QWidget in a QGraphicsView:
QGraphicsView* view = new QGraphicsView(parent);
QGraphicsScene* scene = new QGraphicsScene(view);
view->setScene(scene);
// Widget to rotate - important to not parent it
QWidget* widget = new QWidget();
QProxyWidget proxy_widget = scene_->addWidget(widget);
QPropertyAnimation* animation = new QPropertyAnimation(proxy_widget, "rotation");
animation->setDuration(5000);
animation->setStartValue(0);
animation->setEndValue(360);
animation->setEasingCurve(QEasingCurve::Linear);
animation->start(QAbstractAnimation::DeleteWhenStopped);

Lock app orientation to landscape in Qt

I would like to lock my app developed with Qt to landscape orientation, even if the screen display is portrait. I have tried adding to my code the resizeEvent method found here: http://qt-project.org/doc/qt-4.8/widgets-orientation.html, but my app still does not display correctly. Here is my code for resizeEvent:
void MainWindow::resizeEvent(QResizeEvent *event)
{
QSize size = event->size();
qDebug() << size;
bool isLandscape = size.width() > size.height();
if (isLandscape == false){
size.transpose();
}
this->setFixedSize(size);
}
Does anyone know how to do this in Qt 4.8.5? I am trying to display an app for a 320x240 display.
Thanks
You can't really follow that example. It shows two different widgets depending on the orientation. Furthermore the doc warns about modifying size properties inside resizeEvent.
One solution would be to set a fix aspect ratio similar to 320x240 by overloading QWidget::heightForWidth. You wouldn't need to overload resizeEvent.
It will look like
int MainWindow::heightForWidth( int w ) {
return (w * 240 )/320;
}
heightForWidth is discussed in detail in https://stackoverflow.com/a/1160476/1122645.
edit:
sizeHint is used by the layout of the parent to compute the size of children widgets. In general, it make sense to implement it as
QSize MainWindow::sizeHint() const
{
int w = //some width you seem fit
return QSize( w, heightForWidth(w) );
}
but if MainWindow is top level then it will not change anything. You can also alter heightForWidth flag of your current size policy
QSizePolicy currPolicy = this->sizePolicy();
currPolicy->setHeightForWidth(true);
this->SetSizePolicy(currPolicy);
But again, if it is a top level widget I doesnt change much.
Anyway you don't need to call updateGeometry.