Как сделать фото нужного размера

Transforms on torch.*Tensor¶

class (transformation_matrix, mean_vector)

Transform a tensor image with a square transformation matrix and a mean_vector computed
offline.
Given transformation_matrix and mean_vector, will flatten the torch.*Tensor and
subtract mean_vector from it which is then followed by computing the dot
product with the transformation matrix and then reshaping the tensor to its
original shape.

Applications:

whitening transformation: Suppose X is a column vector zero-centered data.
Then compute the data covariance matrix with torch.mm(X.t(), X),
perform SVD on this matrix and pass it as transformation_matrix.

Parameters
  • transformation_matrix () – tensor , D = C x H x W

  • mean_vector () – tensor , D = C x H x W

class (mean, std, inplace=False)

Normalize a tensor image with mean and standard deviation.
Given mean: and std: for channels, this transform
will normalize each channel of the input i.e.

Note

This transform acts out of place, i.e., it does not mutates the input tensor.

Parameters
  • mean (sequence) – Sequence of means for each channel.

  • std (sequence) – Sequence of standard deviations for each channel.

  • inplace (bool,optional) – Bool to make this operation in-place.

(tensor)
Parameters

tensor () – Tensor image of size (C, H, W) to be normalized.

Returns

Normalized Tensor image.

Return type

Описание свойства Range.Resize

Свойство Range.Resize устанавливает новый размер исходного диапазона по указанному количеству строк и столбцов.

Синтаксис свойства Range.Resize

Expression.Resize(RowSize, ColumnSize)

Конструкция, представляющая синтаксис свойства, не может использоваться отдельно сама по себе, иначе VBA Excel сгенерирует ошибку. Поскольку свойство Range.Resize возвращает диапазон нового размера, его можно присвоить переменной или применить к нему какой-либо метод.

Параметры свойства Range.Resize

Параметр Описание
Expression Выражение, возвращающее исходный диапазон, которому требуется изменить размер. Тип данных параметра — Range.
RowSize Число строк или выражение, возвращающее количество строк нового диапазона. Тип данных параметра — Variant. Если этот аргумент пропущен, число строк в диапазоне останется прежним.
ColumnSize Число столбцов или выражение, возвращающее количество столбцов нового диапазона. Тип данных параметра — Variant. Если этот аргумент пропущен, число столбцов в диапазоне останется прежним.

Параметры RowSize и ColumnSize определяют именно количество строк и столбцов нового диапазона, а не количество добавляемых или вычитаемых из исходного диапазона. Значения аргументов RowSize и ColumnSize должны быть больше нуля, иначе VBA Excel сгенерирует ошибку.

Member Function Documentation

QSizePolicy::QSizePolicy( horizontal, vertical, type = DefaultType)

Constructs a QSizePolicy object with the given horizontal and vertical policies, and the specified control type.

Use () if the preferred height of the widget is dependent on the width of the widget (for example, a QLabel with line wrapping).

This function was introduced in Qt 4.3.

See also (), (), and ().

QSizePolicy::QSizePolicy()

Constructs a QSizePolicy object with as its horizontal and vertical policies.

The policies can be altered using the () and () functions. Use the () function if the preferred height of the widget is dependent on the width of the widget (for example, a QLabel with line wrapping).

See also () and ().

QSizePolicy::controlType() const

Returns the control type associated with the widget for which this size policy applies.

This function was introduced in Qt 4.3.

See also ().

QSizePolicy::expandingDirections() const

Returns whether a widget can make use of more space than the () function indicates.

A value of or means that the widget can grow horizontally or vertically (i.e., the horizontal or vertical policy is or ), whereas | means that it can grow in both dimensions.

See also () and ().

Returns if the widget’s preferred height depends on its width; otherwise returns .

See also ().

Returns if the widget’s width depends on its height; otherwise returns .

See also ().

Returns the horizontal component of the size policy.

See also (), (), and ().

Returns the horizontal stretch factor of the size policy.

See also (), (), and ().

bool QSizePolicy::retainSizeWhenHidden() const

Returns whether the layout should retain the widget’s size when it is hidden. This is by default.

This function was introduced in Qt 5.2.

See also ().

void QSizePolicy::setControlType( type)

Sets the control type associated with the widget for which this size policy applies to type.

The control type specifies the type of the widget for which this size policy applies. It is used by some styles, notably QMacStyle, to insert proper spacing between widgets. For example, the macOS Aqua guidelines specify that push buttons should be separated by 12 pixels, whereas vertically stacked radio buttons only require 6 pixels.

This function was introduced in Qt 4.3.

See also () and ().

void QSizePolicy::setHeightForWidth(bool dependent)

Sets the flag determining whether the widget’s preferred height depends on its width, to dependent.

See also () and ().

Sets the horizontal component to the given policy.

See also (), (), and ().

void QSizePolicy::setHorizontalStretch(int stretchFactor)

Sets the horizontal stretch factor of the size policy to the given stretchFactor. stretchFactor must be in the range .

When two widgets are adjacent to each other in a horizontal layout, setting the horizontal stretch factor of the widget on the left to 2 and the factor of widget on the right to 1 will ensure that the widget on the left will always be twice the size of the one on the right.

See also (), (), and ().

void QSizePolicy::setRetainSizeWhenHidden(bool retainSize)

Sets whether a layout should retain the widget’s size when it is hidden. If retainSize is , the layout will not be changed by hiding the widget.

This function was introduced in Qt 5.2.

See also ().

Sets the vertical component to the given policy.

See also (), (), and ().

void QSizePolicy::setVerticalStretch(int stretchFactor)

Sets the vertical stretch factor of the size policy to the given stretchFactor. stretchFactor must be in the range .

When two widgets are adjacent to each other in a vertical layout, setting the vertical stretch factor of the widget on the top to 2 and the factor of widget on the bottom to 1 will ensure that the widget on the top will always be twice the size of the one on the bottom.

See also (), (), and ().

void QSizePolicy::setWidthForHeight(bool dependent)

Sets the flag determining whether the widget’s width depends on its height, to dependent.

This is only supported for ‘s subclasses. It is not possible to have a layout with both height-for-width and width-for-height constraints at the same time.

See also () and ().

Swaps the horizontal and vertical policies and stretches.

See also ().

QSizePolicy::transposed() const

Returns a size policy object with the horizontal and vertical policies and stretches swapped.

This function was introduced in Qt 5.9.

See also ().

Returns the vertical component of the size policy.

See also (), (), and ().

Returns the vertical stretch factor of the size policy.

See also (), (), and ().

bool QSizePolicy::operator!=(const &other) const

Returns if this policy is different from other; otherwise returns .

See also ().

bool QSizePolicy::operator==(const &other) const

Array methods¶

An object has many methods which operate on or with
the array in some fashion, typically returning an array result. These
methods are briefly explained below. (Each method’s docstring has a
more complete description.)

For the following methods there are also corresponding functions in
: , , ,
, , , ,
, , , ,
, , , ,
, , , ,
, , , , ,
, , ,
, , , ,
, , , ,
, .

Array conversion

(*args) Copy an element of an array to a standard Python scalar and return it.
() Return the array as a (possibly nested) list.
(*args) Insert scalar into an array (scalar is cast to array’s dtype, if possible)
() Construct Python bytes containing the raw data bytes in the array.
() Construct Python bytes containing the raw data bytes in the array.
(fid) Write array to a file as text or binary (default).
(file) Dump a pickle of the array to the specified file.
() Returns the pickle of the array as a string.
(dtype) Copy of the array, cast to a specified type.
(inplace) Swap the bytes of the array elements
() Return a copy of the array.
() New view of array with the same data.
(dtype) Returns a field of the given array as a certain type.
() Set array flags WRITEABLE, ALIGNED, and UPDATEIFCOPY, respectively.
(value) Fill the array with a scalar value.

Shape manipulation

For reshape, resize, and transpose, the single tuple argument may be
replaced with integers which will be interpreted as an n-tuple.

(shape) Returns an array containing the same data with a new shape.
(new_shape) Change shape and size of array in-place.
(*axes) Returns a view of the array with axes transposed.
(axis1, axis2) Return a view of the array with axis1 and axis2 interchanged.
() Return a copy of the array collapsed into one dimension.
() Return a flattened array.
() Remove single-dimensional entries from the shape of a.

Item selection and manipulation

For array methods that take an axis keyword, it defaults to
. If axis is None, then the array is treated as a 1-D
array. Any other value for axis represents the dimension along which
the operation should proceed.

(indices) Return an array formed from the elements of a at the given indices.
(indices, values) Set for all n in indices.
(repeats) Repeat elements of an array.
(choices) Use an index array to construct a new array from a set of choices.
() Sort an array, in-place.
() Returns the indices that would sort this array.
(kth) Rearranges the elements in the array in such a way that value of the element in kth position is in the position it would be in a sorted array.
(kth) Returns the indices that would partition this array.
(v) Find indices where elements of v should be inserted in a to maintain order.
() Return the indices of the elements that are non-zero.
(condition) Return selected slices of this array along given axis.
() Return specified diagonals.

Volume resizing examples

There are multiple ways to resize a volume using vxassist.
1. growto – to grow a volume to a specif volume size
2. growby – to grow a volume by a specific size
3. shrinkto – to shrink a volume to a specific size
4. shrinkby – to shrink a volume by a specific size
The syntax is as follows:

# vxassist -g DG_name  Volume_name size

To find out the current size of the volume:

# /opt/VRTSsfmh/bin/vxlist vol
TY   VOLUME   DISKGROUP         SIZE STATUS    LAYOUT   LINKAGE
vol  myvol    mydg          1324.05m healthy   concat   -

To grow the volume myvol by 100mb

# vxassist -g mydg growby myvol 100m
# /opt/VRTSsfmh/bin/vxlist vol
TY   VOLUME   DISKGROUP         SIZE STATUS    LAYOUT   LINKAGE
vol  myvol    mydg          1424.05m healthy   concat   -

To shrink volume myvol by 100m (use -f incase of error, use it carefully as it may damage the data)

# vxassist -g mydg shrinkby  myvol 100m
# /opt/VRTSsfmh/bin/vxlist vol
TY   VOLUME   DISKGROUP         SIZE STATUS    LAYOUT   LINKAGE
vol  myvol    mydg          1324.05m healthy   concat   -

To grow volume myvol to 1600 MB

# vxassist -g mydg growto myvol 1600m
# /opt/VRTSsfmh/bin/vxlist vol
TY   VOLUME   DISKGROUP         SIZE STATUS    LAYOUT   LINKAGE
vol  myvol    mydg          1600.00m healthy   concat   -

Now we can similarly shrink the volume to a specific size. I had to use -f to force the shrink.

# vxassist -g mydg -f shrinkto myvol 1500m
# /opt/VRTSsfmh/bin/vxlist vol
TY   VOLUME   DISKGROUP         SIZE STATUS    LAYOUT   LINKAGE
vol  myvol    mydg          1500.00m healthy   concat   -

Arithmetic, matrix multiplication, and comparison operations¶

Arithmetic and comparison operations on
are defined as element-wise operations, and generally yield
objects as results.

Each of the arithmetic operations (, , , , ,
, , or , , , ,
, , ) and the comparisons (, , ,
, , ) is equivalent to the corresponding
universal function (or for short) in NumPy. For
more information, see the section on .

Comparison operators:

x.__lt__(y) x
x.__le__(y) x
x.__gt__(y) x>y
x.__ge__(y) x>=y
x.__eq__(y) x==y
x.__ne__(y) x!=y

Truth value of an array ():

x.__nonzero__() x != 0

Note

Truth-value testing of an array invokes
, which raises an error if the number of
elements in the array is larger than 1, because the truth value
of such arrays is ambiguous. Use and
instead to be clear about what is meant
in such cases. (If the number of elements is 0, the array evaluates
to .)

Unary operations:

x.__neg__() -x
x.__pos__() +x
()  abs(x)
x.__invert__() ~x

Arithmetic:

x.__add__(y) x+y
x.__sub__(y) x-y
x.__mul__(y) x*y
x.__div__(y) x/y
x.__truediv__(y) x/y
x.__floordiv__(y) x//y
x.__mod__(y) x%y
(y)  divmod(x, y)
(y)  pow(x, y)
x.__lshift__(y) x
x.__rshift__(y) x>>y
x.__and__(y) x&y
x.__or__(y) x|y
x.__xor__(y) x^y

Note

  • Any third argument to is silently ignored,
    as the underlying takes only two arguments.
  • The three division operators are all defined; is active
    by default, is active when
    division is in effect.
  • Because is a built-in type (written in C), the
    special methods are not directly defined.
  • The functions called to implement many arithmetic special methods
    for arrays can be modified using .

Arithmetic, in-place:

x.__iadd__(y) x+=y
x.__isub__(y) x-=y
x.__imul__(y) x*=y
x.__idiv__(y) x/=y
x.__itruediv__(y) x/y
x.__ifloordiv__(y) x//y
x.__imod__(y) x%=y
x.__ipow__(y) x**=y
x.__ilshift__(y) x
x.__irshift__(y) x>>=y
x.__iand__(y) x&=y
x.__ior__(y) x|=y
x.__ixor__(y) x^=y

Warning

In place operations will perform the calculation using the
precision decided by the data type of the two operands, but will
silently downcast the result (if necessary) so it can fit back into
the array. Therefore, for mixed precision calculations, can be different than . For example, suppose
. Then, is different than : while they both perform the same computation,
casts the result to fit back in , whereas
re-binds the name to the result.

Matrix Multiplication:

Resizing both volume and file system online using vxresize

All the command used above changes only the size of the underlying volume. To increase the size of volume as well as the file system above it, we can use vxresize. Let us see an example, I have a mount point /data on top of the volume myvol.

# df -h |grep data
/dev/vx/dsk/mydg/myvol   1.5G    17M   1.4G     2%    /data
# /opt/VRTSsfmh/bin/vxlist vol
TY   VOLUME   DISKGROUP         SIZE STATUS    LAYOUT   LINKAGE
vol  myvol    mydg          1500.00m healthy   concat   -

Lets now increase the volume as well as FS by 100MB

# vxresize -g mydg myvol 1600m

Now you can see both FS and volume size has been increased by 100MB

# df -h |grep data
/dev/vx/dsk/mydg/myvol   1.6G    17M   1.4G     2%    /data
# /opt/VRTSsfmh/bin/vxlist vol
TY   VOLUME   DISKGROUP         SIZE STATUS    LAYOUT   LINKAGE
vol  myvol    mydg          1600.00m healthy   concat   -

I hope the article was informative. Do comment if you have any doubts.

Internal memory layout of an ndarray¶

An instance of class consists of a contiguous
one-dimensional segment of computer memory (owned by the array, or by
some other object), combined with an indexing scheme that maps N
integers into the location of an item in the block. The ranges in
which the indices can vary is specified by the of the array. How many bytes each item takes and how
the bytes are interpreted is defined by the associated with the array.

A segment of memory is inherently 1-dimensional, and there are many
different schemes for arranging the items of an N-dimensional array
in a 1-dimensional block. NumPy is flexible, and
objects can accommodate any strided indexing scheme. In a strided
scheme, the N-dimensional index
corresponds to the offset (in bytes):

from the beginning of the memory block associated with the
array. Here, are integers which specify the of the array. The order (used,
for example, in the Fortran language and in Matlab) and
order (used in C) schemes are just specific kinds of
strided scheme, and correspond to memory that can be addressed by the strides:

where = self.shape.

Both the C and Fortran orders are , i.e.,
single-segment, memory layouts, in which every part of the
memory block can be accessed by some combination of the indices.

While a C-style and Fortran-style contiguous array, which has the corresponding
flags set, can be addressed with the above strides, the actual strides may be
different. This can happen in two cases:

Point 1. means that and always have the same
contiguity and aligned flags value. This also means that even a high
dimensional array could be C-style and Fortran-style contiguous at the same
time.

An array is considered aligned if the memory offsets for all elements and the
base offset itself is a multiple of self.itemsize.

Note

Points (1) and (2) are not yet applied by default. Beginning with
NumPy 1.8.0, they are applied consistently only if the environment
variable was defined when NumPy
was built. Eventually this will become the default.

You can check whether this option was enabled when your NumPy was
built by looking at the value of . If this is , then your
NumPy has relaxed strides checking enabled.

Warning

It does not generally hold that
for C-style contiguous arrays or for
Fortran-style contiguous arrays is true.

Data in new is in the
(C) order, unless otherwise specified, but, for example, often produces
in a different scheme.

Special methods¶

For standard library functions:

() Return a copy of the array.
(() -> Deep copy of array.) Used if copy.deepcopy is called on an array.
() For pickling.
(version, shape, dtype, …) For unpickling.

Basic customization:

((S, …)
(…) Returns either a new reference to self if dtype is not given or a new array of provided data type if dtype is different from the current dtype of the array.
(…)

Container customization: (see )

()  len(x)
x.__getitem__(y) x
x.__setitem__(i, y) x=y
x.__contains__(y) y in x

Conversion; the operations , ,
, , , and
. They work only on arrays that have one element in them
and return the appropriate scalar.

()  int(x)
()  long(x)
()  float(x)
()  oct(x)
()  hex(x)

String representations:

()  str(x)
()  repr(x)

Трюки с textarea

В статье представлено несколько трюков, которые вы, возможно, не знали и которые вы найдёте полезными в своих разработках.

1. Изображение в качестве фона, которое пропадает при вводе текста.

Вы можете добавить фоновое изображение также, как и в любой другой элемент. В этом случае стиль по умолчанию для textarea изменяется, а именно бордер толщиной в 1px изменяется на скошенную границу. Исправляется это явным указанием бордера.

Фоновое изображение может повлиять на читаемость текста. Поэтому фоновое изображение надо убирать при получении фокуса и возвращать его, если textarea осталась без текста. Например, используя jQuery это можно сделать таким образом:

2. Placeholder в HTML5

В HTML5 появился новый атрибут, называемый placeholder. Значение этого атрибута показывается в текстовом элементе и исчезает при получении фокуса, а также в случае когда в элементе введён текст.

HTML5 placeholder поддерживается в следующих браузерах: Safari 5, Mobile Safari, Chrome 6, и Firefox 4 alpha.

3. Placeholder, HTML5 с поддержкой старых браузеров используя jQuery

Самый простой способ проверить поддерживается ли атрибут браузером это проверить с помощью javaScript:

Затем можно написать код, который будет срабатывать если браузер не поддерживает атрибут placeholder.

4. Удаляем обводку textarea

Браузеры на движках webkit, а также в FireFox 3.6, обводят textarea, когда он находится в фокусе. Удалить эту обводку можно используя css-свойство outline для webkit-браузеров. Для FireFox используется свойство -moz-appearance, либо можно просто установить элементу бордер или фон.

5. Запрет изменения размера

Webkit-браузеры добавляют к textarea визуальный элемент в правом нижнем углу, который позволяет изменять размер текстовой области. Если вы хотите убрать эту возможность, то вам необходимо использовать следующее css-свойство:

6. Добавление возможности изменения размера

jQuery UI позволяет добавить возможность изменения размера для textarea. Это работает для всех браузеров, а для webkit-браузеров подменяет стандартное поведение. Для того, чтобы использовать эту возможность, необходимо подключить jquery.ui и написать следующий код:

7. Изменение размера под содержимое

James Padolsey написал удобный jQuery-скрипт который позволяет автоматически изменять размер textarea под его содержимое. Похоже что этого плагина больше нет, но можно использовать например вот этот. Плагин содержит много настроек, но самый простой способ его использовать это:

8. Nowrap

Чтобы не переносить слова на новые строки, для всех элементов используется css-свойство white-space, которое не работает с textarea. Для textarea необходимо использовать атрибут wrap.

9. Удаляем скролл-бары в IE

IE показывает вертикальный скролл-бар для всех textarea. Вы можете их спрятать используя overflow: hidden, но в таком случае он не будет показываться при увеличении контента. Поэтому правильнее использовать следующий подход:

В этом случае скролл-бар не будет отображаться когда в textarea помещается весь текст, но выведется в случае необходимости.

Примеры к статье вы можете посмотреть здесь.

Array attributes¶

Array attributes reflect information that is intrinsic to the array
itself. Generally, accessing an array through its attributes allows
you to get and sometimes set intrinsic properties of the array without
creating a new array. The exposed attributes are the core parts of an
array and only some of them can be reset meaningfully without creating
a new array. Information on each attribute is given below.

Memory layout

The following attributes contain information about the memory layout
of the array:

Information about the memory layout of the array.
Tuple of array dimensions.
Tuple of bytes to step in each dimension when traversing an array.
Number of array dimensions.
Python buffer object pointing to the start of the array’s data.
Number of elements in the array.
Length of one array element in bytes.
Total bytes consumed by the elements of the array.
Base object if memory is from some other object.

Data type

See also

The data type object associated with the array can be found in the
attribute:

Data-type of the array’s elements.

Other attributes

Same as self.transpose(), except that self is returned if self.ndim
The real part of the array.
The imaginary part of the array.
A 1-D iterator over the array.
An object to simplify the interaction of the array with the ctypes module.

А теперь подробнее

Функция autoResize может принимать следующие параметры:

onResize Функция вызывается каждый раз в момент изменения размера textarea. Доступиться к textarea внутри функции можно как к ‘this’. функция
animate Анимация изменения высоты. Значение true — анимация есть, false — анимации нет. Значение по-умолчанию: true. boolean
animateDuration Время, которое занимает анимация в миллисекундах. Значение по-умолчанию: 150. число
animateCallback Функция вызывается каждый раз, как только заканчивается анимация. функция
extraSpace Количество пикселей которые будут добавлены к высоте textarea — дополнительный внутренний отступ снизу. Значение по-умолчанию: 20. число
limit По достижению этой высоты в пикселях текстовое поле перестает расширятся. Значение по-умолчанию: 1000. число

Примеры:

Отключаем дополнительный отступ снизу (по умолчанию он составляет 20px):

jQuery('textarea').autoResize({
     extraSpace : 0
});

Кстати, этот отступ (extraSpace) дает забавный эффект. Поскольку добавляется он к textarea не изначально, а только при первом вводе, то и текстовое поле при первом вводе внезапно расширяется (на величину extraSpace). Такой скачек может показаться нелогичным — ведь поле изначально может быть высоким и места в нем еще много, а оно все равно расширилось! Чтобы такого не происходило, можно инициализировать ресайз с параметром extraSpace : 0 (как в примере выше).

Демонстрация анимации при ресайзе:

	jQuery('textarea').autoResize({
	 	// On resize:
		onResize : function() {
			jQuery(this).css({color:'#fff', backgroundColor:'#999'});
		},
		// After resize:
		animateCallback : function() {
			jQuery(this).css({color:'#000', backgroundColor:'#fff'});
		}
	});

Заметка

Функция animateCallback будет вызываться, только если для textarea в CSS задать display:block (притом, исходя из текста плагина, сделано это специально). Учти, что этот самый display:block (если мы ему не помешаем) вызовет появление в Opera полос прокрутки. Для того, чтобы такого сюрприза не случилось используем overflow:hidden.

textarea{
	width:400px;
	height:70px;
	overflow:hidden;
	display:block;
}

Проверено в:

  • IE 6-8
  • Firefox 3.5
  • Opera 9.5-10
  • Safari 3

Maxsize Vs maxgrow

The syntax to find the space remaining in a DG using maxsize is :

# vxassist -g DG_name maxsize layout=Layout

For example the maximum size mirrored volume that can be created in Disk group mydg can be found out by using :

# vxassist -g mydg maxsize layout=mirror
Maximum volume size: 1820672 (889Mb)

To find out maxsize of volumes with different layouts just change the layout attribute to raid5, concat, stripe-mirror etc.

Now we can find the size to which an existing volume can grow using the maxgrow. There is a difference in maxgrow and maxsize. Maxsize is used to find the size to which a new volume can be grown to and maxgrow is to find the size to which an existing volume can be grown to. The syntax of using maxgrow with vxassist is :

# vxassist -g DG_name maxgrow Volume_name

for example

# vxassist -g mydg maxgrow myvol
Volume myvol can be extended by 1955840 to: 4052992 (1979Mb)

Now this is tricky, the size 1979Mb is the final size to which the volume can grow to if it uses the complete space in the DG. So even when I grow it by 100MB and see the output of maxgrow command it would again show me that the myvol can be grown to 1979Mb size. In that case you can use the maxsize command to see the remaining space in the DG.

Member Type Documentation

enum QSizePolicy::ControlTypeflags QSizePolicy::ControlTypes

This enum specifies the different types of widgets in terms of layout interaction:

Constant Value Description
The default type, when none is specified.
A QDialogButtonBox instance.
A QCheckBox instance.
A QComboBox instance.
A QFrame instance.
A QGroupBox instance.
A QLabel instance.
A QFrame instance with or .
A QLineEdit instance.
A QPushButton instance.
A QRadioButton instance.
A QAbstractSlider instance.
A QAbstractSpinBox instance.
A QTabWidget instance.
A QToolButton instance.

This enum was introduced or modified in Qt 4.3.

The ControlTypes type is a typedef for QFlags. It stores an OR combination of ControlType values.

See also () and ().

enum QSizePolicy::Policy

This enum describes the various per-dimension sizing types used when constructing a QSizePolicy.

Constant Value Description
The () is the only acceptable alternative, so the widget can never grow or shrink (e.g. the vertical direction of a push button).
The sizeHint() is minimal, and sufficient. The widget can be expanded, but there is no advantage to it being larger (e.g. the horizontal direction of a push button). It cannot be smaller than the size provided by sizeHint().
The sizeHint() is a maximum. The widget can be shrunk any amount without detriment if other widgets need the space (e.g. a separator line). It cannot be larger than the size provided by sizeHint().
The sizeHint() is best, but the widget can be shrunk and still be useful. The widget can be expanded, but there is no advantage to it being larger than sizeHint() (the default QWidget policy).
The sizeHint() is a sensible size, but the widget can be shrunk and still be useful. The widget can make use of extra space, so it should get as much space as possible (e.g. the horizontal direction of a horizontal slider).
The sizeHint() is minimal, and sufficient. The widget can make use of extra space, so it should get as much space as possible (e.g. the horizontal direction of a horizontal slider).
The sizeHint() is ignored. The widget will get as much space as possible.

See also , (), and ().

enum QSizePolicy::PolicyFlag

These flags are combined together to form the various values:

Constant Value Description
The widget can grow beyond its size hint if necessary.
The widget should get as much space as possible.
The widget can shrink below its size hint if necessary.
The widget’s size hint is ignored. The widget will get as much space as possible.

Detailed Description

The size policy of a widget is an expression of its willingness to be resized in various ways, and affects how the widget is treated by the layout engine. Each widget returns a QSizePolicy that describes the horizontal and vertical resizing policy it prefers when being laid out. You can change this for a specific widget by changing its property.

QSizePolicy contains two independent values and two stretch factors; one describes the widgets’s horizontal size policy, and the other describes its vertical size policy. It also contains a flag to indicate whether the height and width of its preferred size are related.

The horizontal and vertical policies can be set in the constructor, and altered using the () and () functions. The stretch factors can be set using the () and () functions. The flag indicating whether the widget’s is width-dependent (such as a menu bar or a word-wrapping label) can be set using the () function.

The current size policies and stretch factors be retrieved using the (), (), () and () functions. Alternatively, use the () function to swap the horizontal and vertical policies and stretches. The () function returns the current status of the flag indicating the size hint dependencies.

Use the () function to determine whether the associated widget can make use of more space than its function indicates, as well as find out in which directions it can expand.

Ссылка на основную публикацию