[Qt]的Layout边缘空白调整



原创文章,欢迎转载。转载请注明:转载自 祥的博客

原文链接:https://blog.****.net/humanking7/article/details/88064393


Qt的Layout边缘空白调整

最终效果:
[Qt]的Layout边缘空白调整

1.问题

设计了一个窗口控件,继承了QWidget,里面有两个QLabel,用QHBoxLayout将其并排排列。但是这个控件被调用,但是这个控件边缘太大,看起来很丑,主要原因就是这个QHBoxLayout的边缘设置的太大。

这个窗口控件有3个文件:

  • LedLabel.h
  • LedLabel.cpp
  • LedLabel.ui

[Qt]的Layout边缘空白调整
下图:边缘太大
[Qt]的Layout边缘空白调整

下图:边缘设置为0后的效果
[Qt]的Layout边缘空白调整

2.边缘太大原因

边缘太大就是因为LedLabel.ui会自动生成一个文件ui_LedLabel.h,在这个里面有一段代码,将整体的这个QHBoxLayout的边缘默认设置的比较大

class Ui_LedLabel
{
public:
    QHBoxLayout *horizontalLayout;
    QLabel *lab_LED;
    QLabel *lab_TXT;

    void setupUi(QWidget *LedLabel)
    {
		//....
		// 这个将边缘设置的太大,这样看来很丑
        horizontalLayout->setContentsMargins(11, 11, 11, 11);
        //....        
    } // setupUi

    void retranslateUi(QWidget *LedLabel)
    {
        //....
    } // retranslateUi

};

[Qt]的Layout边缘空白调整

3.解决方法

解决方法,就是在这个控件类的构造函数中自己设置这个边缘,将其设置为0(当然可以选择自己觉得ok的尺寸)

LedLabel::LedLabel(QWidget *parent , QString str)
	: QWidget(parent)
{
	ui.setupUi(this);
	updateUI(0, str );
	
	//设置边界为0 
	//没有这行代码,边界会非常大,很难看
	ui.horizontalLayout->setContentsMargins(0, 0, 0, 0);	

}

4.关于函数setContentsMargins()

void QLayout::setContentsMargins(int left, int top, int right, int bottom)
/*
Sets the left, top, right, and bottom margins to use around the layout.
By default, QLayout uses the values provided by the style. On most platforms, the margin is 11 pixels in all directions.

This function was introduced in Qt 4.3.

See also contentsMargins(), getContentsMargins(), QStyle::pixelMetric(), PM_LayoutLeftMargin, PM_LayoutTopMargin, PM_LayoutRightMargin, and PM_LayoutBottomMargin.
*/
    
void QLayout::setContentsMargins(const QMargins & margins)
/*
Sets the margins to use around the layout.

By default, QLayout uses the values provided by the style. On most platforms, the margin is 11 pixels in all directions.

This function was introduced in Qt 4.6.
*/

5.扩展

QLabel的显示圆形: https://blog.****.net/humanking7/article/details/88065087
Qt的Layout边缘空白调整: https://blog.****.net/humanking7/article/details/88064393
Qt状态栏QStatusBar使用: https://blog.****.net/humanking7/article/details/88065425

[Qt]的Layout边缘空白调整


[Qt]的Layout边缘空白调整