How do you make Interface Builder respect a custom view's intrinsic content size in constraint based layout? - xcode4

Interface Builder in XCode 4.5 respects the intrinsicContentSize for some views, e.g. NSButton, but I can't convince it to respect it on my own custom subviews. This causes IB to add extra constraints trying to force the layout drawn in IB, which then causes the intrinsic sizes to not be used when the program is run.
For example, consider a button centered in a window, and a custom view centered in a window…
You can see that the custom view gets four constraints, presumably because IB doesn't know the view's intrinsicContentSize. You can change which extra constraints are added, e.g. you can force it to be width and height instead, but you can't delete them.
I'm coping with this now by searching and deleting the extra constraints in my awakeFromNib, but there must be a better way to do this.

Set a placeholder intrinsic content size — a "guess," if you will — in Interface Builder.
Select your custom view.
Show the size inspector (⌘Shift5).
Change the "Intrinsic Size" drop-down from "Default (System Defined)" to "Placeholder."
Enter reasonable guesses at your view's runtime width and height.
These constraints are removed at compile-time, meaning they will have no effect on your running app, and the layout engine will add constraints as appropriate at runtime to respect your view's intrinsicContentSize.

How to actually do this, 2019
import UIKit
#IBDesignable class TagPerson: ShadowRoundedImageView {
override var intrinsicContentSize: CGSize {
var s = super.intrinsicContentSize
s.height = 40
s.width = 40
return s
}
override func prepareForInterfaceBuilder() {
invalidateIntrinsicContentSize()
}
}
However, there is a problem. Xcode is buggy. You can sometimes reset it by:
The above will of course work flawlessly at runtime. But it randomly fails to work in interface builder (even with 11+).
To make it cycle, try
The usual 'Refresh all views'
Attach and delete a pointless constraint to one of your intrinsic size views. (I've noticed if you have a number of them, doing this to one is usually enough to make Xcode cycle, then they all work.)
And finally:
Xcode has an "intrinsic size placeholder" feature.
Select one or more of your intrinsic-size elements. Toggle the bizarre placeholder thing back and fore a few times. Often that makes it cycle and the view will then work correctly.
At worst, restarting Xcode with the usual clean-everything will, sometimes, get it working.

Ok, the point here is to make Xcode use the intrinsicContentSize of your custom view in IB.
This can be achieved by adding a placeholder view inside your custom view in IB with a fixed width and height (you can center it horizontally and vertically as well)
Then select your custom view and tap "Size To Fit Content" form the Edit Menu in IB.
At this point all extra size defining constraints will be deletable leaving only positioning ones.
That way IB will size your custom view to fit the placeholder view and and Autolayout would depend on your view's override of - (CGSize)intrinsicContentSize in run time to determine your custom view's size.
Last step is to delete the placeholder view to allow your view to display its content and size correctly:
- (void)viewDidLoad
{
[super viewDidLoad];
[_placeholderView removeFromSuperview];
}
I know this is a hack but hopefully it helps you.

Related

iOS 13 UITableViewCell | Child view gets clipped out

SO I have a UITableView which contains a UITableViewCell and tableView.header is set to a Parallax Header. The UITableViewCell has certain UIViews which are set as negative constraints from Top and are shown perfectly on iOS-12 whereas when observed on iOS-13 the UIViews showing over Parallax Header are clipped. I have tried all possible solutions but unfortunately it still shows the same. My App is opting out of SwiftUI and still running the old code. I have even tried to change the zIndex of the child UIView but still the same. Here are some snapshots and some code:
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.PriceView.layer.zPosition = 1
self.PriceView.bringSubviewToFront(self.contentView)
self.PriceView.setNeedsDisplay()
}
This code is functional for iOS-12 but not iOS-13.
UPDATE:
Apple's changelog/documentation for iOS-13 suggests:
The UITableViewCell class’s contentView property is always laid out
edge-to-edge with adjacent accessories, both on the leading and the
trailing side. This streamlines the layout code so developers who want
the correct default offset no longer have to align their content with
the content view border or the layout margin depending on whether
there is an accessory on the trailing side or not. You should now
always lay out their code on the layout margins of the cell’s content
view to get the default system insets. These insets will be adjusted
automatically based on the accessories visible in the cell to match
the system’s default spacing. (48214114)
This is a bit unclear to me and if someone can help me out here.
Here are the snapshots as to how it is showing in iOS-12 which is required and how it is showing in iOS-13 respectively:
And here observe for iOS-13:
Here is also the Constraint Layout of my UITableViewCell's PriceView:
I need both to be consistent on both OSes. THANK YOU SO MUCH FOR THIS HELP!
Wohoo! I finally figured it out. So before as default it was working on iOS-12 but after iOS-13 and UITableViewCell changes as described in the question, it stopped working. Here is what I did:
Firstly, in the Size Inspector, the ContentView of UITableViewCell was set to Safe Area Layout Guide which I turned off and turned on Safe Area Relative Margins, similarly I did the same for the child, as in the PriceView.
Secondly, in the Attributes Inspector, the ContentView's and UITableViewCell's both had their Autoresize Subviews property turned on, I simply turned it off
And voila! It works. Hope anyone who might have these UITableViewCell issues, please note that now its all relative 😉
Actually, what worked for me was unchecking "clip to bounds" from the attribute inspector for the content view

Resizing Layout equal to MainWindow

When I run my program it will display all content properly, and when I resizing the main window, the layout along with all associated widgets remain fixed, rather than resizing with the main window. I used to increase my all widget and listWidget respect to window computer resolution size but still this not one work properly.
I used this one code finding the system height and width.
QWidget widget;
widget.resize(widget.width(), widget.minimumHeight());
QRect rec = QApplication::desktop()->screenGeometry();
int h = rec.height();
int w = rec.width();
// Increasing the listwidget size
ui->listWidget->setFixedHeight(h);
ui->listWidget->setFixedWidth(w);
//increasing the button size
ui->pushButton->setFixedHeight(h0.2);
ui->pushButton->setFixedWidth(w0.2);
At this link you will find two screenshots that illustrate my problem.
Please resolve to solve my problem. Thanks very much in advance.
When defining the layout of your windows and forms in Qt Designer you have to define each element of your form in advance, in order to have a working layout.
This solution is based on the screenshots provided in the comments to the question. Follow these steps:
Add an empty widget to the central area of your form, if there is nothing there. It will be used as a placeholder for the controls you will add later, and of course you can replace it with whatever widget you want. But you need it there to define a proper layout.
In the property panel, set the horizontal QSizePolicy of this widget to MinimumExpanding.
Add an horizontal spacer to the left side of your progress bar.
Define a minimum/maximum width for the white widget on the left (I guess it's a text area). As an example set the maximum width to 200
pixels.
Make the same for the QTabWidget on the right.
Give a minimum height to the Groupbox on top.
Then give the grid layout to the MainWindow.
You should get something similar in the designer view (I use a dark theme, yours will have different colors of course):
If you complete all steps you should have a nicely resizing window.
For the future: remember to integrally define your layouts, also using placeholder widgets when needed, read carefully the documentation about the widgets size policies (there are several, you need to play with them to fully understand each one) and keep in mind that Qt uses a container based approach which is different, as an example from those used by the .Net framework that relies on the concept of anchors.
EDIT : to answer questions in the comments
You will need to add a layout to any widget that contains other widgets, e.g. adding controls to your groupbox will require to give it a grid, horizontal or vertical layout in order to scale nicely on resize. Again use spacers and size policies to make it look the way you want. If you need to add or remove controls, or change their positions, you may need to brake the layout, rearrange and then set it again.
You can also select groups of widgets and give them a layout e.g. vertical, than another group and set them horizontal and so on... then give a grid layout to the container widget to build a compound layout.
There are endless possibilities, you just need to practice and go through trial and error as for everything else...
You can also do it all programmatically, check the Qt widgets documentation for this. But for complex layouts I would not go that way: it's a lot of code... and you have to compile and run to test every modification.
Using the QtCreator, within the designer you can simply right-click on the parent-widget and add a Grid-Layout.
This one resizes it's children to it's dimensions.

Qt Layout, resize to minimum after widget size changes

Basically I've got a QGridLayout with a few widgets in it. The important ones are 2 labels, which I use for drawing images to the screen. Well, if the user wants, he can change the resolution of the incoming images, thus, forcing the Labels to resize.
Let's assume the initial size of the label is 320x240. The user changes the VideoMode to 640x480, the label and the entire GUI resizes perfectly. But when the user switches back to 320x240, the label shrinks, but the Layout/Window does NOT.
I've played around with sizePolicies and sizeHints, and resize(0,0), but nothing did the trick. Could somebody help me with this?
Here some screenshots to clarify the problem:
You need to set the size constraint of the layout holding all your widgets to "SetFixedSize". Although the name doesn't sound like it will work, it ensures that your layout will only use the space it needs. You will not have the problem like you do in your second screenshot.
Example:
mainLayout.setSizeConstraint(QLayout::SetFixedSize);
QLayout::setSizeConstraint(QLayout::SetFixedSize) solves this problem well when you prefer keeping your widget's size fixed at all times--that is, if you'd like it to always be fixed to its "packed" size (which may still vary as the child widgets change size). That is what the "fixed" means there: "fixed" to the correct size, even as the latter varies. (In Qt terms, what I'm calling the "packed" size is simply the widget's sizeHint.)
But a constraint may be too strong a solution in some instances. In particular, if you apply it to a top-level window, then the user will not be free to resize the window. If you don't like that, you can instead perform the "set size to sizeHint" operation instantaneously each time it's needed, rather than imposing it as an unrelenting constraint. The way to do that is to call QWidget::adjustSize().
http://doc.qt.io/qt-5/qwidget.html#adjustSize
Note that if the container whose children are changing size is not the top-level window, then adjustSize() may have to be called recursively on the container and its parents. (In my case I had to do that, anyway. I also tried the size-constraint scheme, and found that applying the constraint at only the topmost level was successful in compacting all levels. I haven't enough knowledge of Qt to comment usefully on these observations, so I merely share them.)
You need to store the original size of your widget parent window before applying any changes to the layout and restore it when the user switches back to the original.
Notice that you need to work with the widget parent window size and not the widget parent size.
in your widget before applying the layout changes:
minimumWindowSize = this->window().size();
when you finished reorganizing the widget to the compact size
this->window().resize(minimumWindowSize);
So that is exactly what i'm doing in mu project.
Resolution os doesn't matter. I have only to have a widget for rendering video, or image in your case.
void MainWindow::resizeEvent(QResizeEvent* event)
{
QMainWindow::resizeEvent(event);
if ((player != 0) && ((player->isPlaying()) || player->isLoaded() || player>isLoaded())){
renderer->resize(ui->mainVideoWidget->width(),ui->mainVideoWidget->height());
resizeFilter();
}
}

Auto-sizing and positioning in Flex

I am working on a flex app that uses XML templates to dynamically create DisplayObjects. These templates define different layouts that can be used for each page of content in the app (ie , 2 columns, 3 columns etc etc). The administrator can select from one of these and populate each area with their content.
The templates add one of 3 types of DisplayObject - HBox, VBox or a third component - LibraryContentContainer (an mxml component that is defined as part of the app) - which is effectively a canvas element with a TextArea inside.
The problem that I am getting is that I need each of these areas to automatically resize to fit the length of the content but don't seem to be able to find an effective way to do so.
In the LibraryContentContainer, when the value of the TextArea is set, I am calling .validateNow() on the LibraryContentContainer. I then set the height property on both the TextArea and LibraryContentContainer to match the textHeight property of the TextArea.
In the following example, this is the LibraryContentContainer, viewer is the TextArea and the value property of the TextArea is bound to this.__Value. v is the variable containing the content for the textarea
this.__Value = v;
this.validateNow();
this.viewer.height = this.viewer.textHeight;
this.height = this.viewer.height;
This works to a degree in that the TextArea grows or shrinks depending on the length of content, but it's still not great - sometimes there are still vertical scrollbars even tho the size of the TextArea has grown.
Anyone got any ideas?
Thanks
Adam
I think the problem lies not with your dynamically added components, but with the component they're being added to. How is the height of this component being determined? If you set verticalScrollPolicy and horizontalScrollPolicy on this container to off, do your scrollbars disappear? If that's the case, then you'll need to look at how this component is sized rather than your hbox, vbox, or whatever it is you're adding.

Non-resizeable QDialog with fixed size in Qt?

I have a Qt dialog application. Now I dont want that dialog to be resizeable. I am not sure how to achieve this. I tried a bunch of things but still when the dialog launches this dialog can be resized.
What is the property that i should set to disable the dialog/Widget resize.
I also tried
setSizePolicy(QSizePolicy::Fixed);
But i get an error saying..
source\nimcac_settingsMain.cpp(36) : error C2248:
**'QSizePolicy::QSizePolicy' : cannot access private member declared in class 'QSizePolicy'**
p:\ThirdPartyExports\Qt\export\4.3\4.3.1f14\include\QtGui\../../src\gui\
kernel\qsizepolicy.h(177) : see declaration of 'QSizePolicy::QSizePolicy'
p:\ThirdPartyExports\Qt\export\4.3\4.3.1f14\include\QtGui\../../src\gui\
kernel\qsizepolicy.h(34) : see declaration of 'QSizePolicy'
Kindly help me out with this.
The compile error you get is because you try to pass a QSizePolicy::Policy to setSizePolicy(QSizePolicy), but there's no implicit conversion from QSizePolicy::Policy (which is the policy for one dimension) to QSizePolicy (which is a class containing, among other things, one Policy per dimension (height, width)). QSizePolicy doesn't work on top-level widgets (windows) anyway, though.
setFixedSize() only works if you know the size of the dialog in advance (and usually you don't, what with changing font sizes and languages). You can do
window()->setFixedSize( window()->sizeHint() );
but it's much better to use
window->layout()->setSizeConstraint( QLayout::SetFixedSize );
That lets the layout determine the size of the dialog, but doesn't allow resizing, which I assume is what you were asking for.
I don't know if you already tried it, but QWidget::setFixedSize should do what you want
this->setFixedSize(this->width(),this->height());
You need to change the windowFlags of the dialog and set it to Qt::MSWindowsFixedSizeDialogHint.
This only works in windows.
For more information please see this example:
http://doc.qt.digia.com/4.5/widgets-windowflags.html
On QT Creator, in the UI editor, click on the top object in the properties window, then scroll at the bottom in the Layout part. You should see the layoutSizeConstraint property.
Set the layoutSizeConstraint to SetFixedSize.
If you use QtCreator (of course you are) you can set the property HorizontalsizePolicy to fixed and Vertical Policy also to Fixed. Then you can set the maximumSize to the dimensions you want. The window will not maximise again.
In code you can do something like this,
Dialog->resize(581, 292);
QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(WaterLevelEditorDialog->sizePolicy().hasHeightForWidth());
Dialog->setSizePolicy(sizePolicy);
Dialog->setMinimumSize(QSize(581, 292));
Dialog->setMaximumSize(QSize(581, 292));
Dialog->setSizeGripEnabled(false);
In QtCreator do as follows,
Select the dialog box widget
Locate the dialog box widget in Object Window
In Object Window, right click on dialog box object to popup a menu
Select "Size Constraints" -> "Set Maximum Size" from the menu
Right click again on dialog object to popup a menu
Select "Size Constraints" -> "Set Minimum Size"
In Property Window,
ensure "sizePolicy"->"Horizontal Policy" has value "Fixed"
ensure "sizePolicy"->"Vertical Policy" has value "Fixed"
ensure "sizeGripEnabled" is not checked
From the Qt documentation, setSizePolicy() method either takes zero argument or two arguments but cannot be one argument. That's why you get this compilation error. From my experiment, if you don't set the fixed size. This method has no use. The window can still be resizable.
An easier way is to set the maxium size to 0.
this->setMaxiumSize(QSize(0, 0));
In case you are designing UI in QML and launching using QDeclarativeView, try the below code.
QScopedPointer<QmlApplicationViewer> viewer(QmlApplicationViewer::create());
.
.
.
//To make the window non-resizable
viewer->setFixedSize(viewer->width(),viewer->height());
Here QmlApplicationViewer is derived from QDeclarativeView.

Resources