What could be causing the excessive space between dynamic buttons in a grid layout?

I am developing an application using Qt. Within the mainwindow.cpp file, I have a frame that displays another widget. This widget is populated with QPushButtons generated dynamically from the database. The maximum limit for buttons is set at 8. Here is the code snippet responsible for creating the buttons:

 for(int i = 0; i < btnlst.count(); ++i)
    {
        QPushButton *b = new QPushButton(this);
        b->setStyleSheet("background-color: qlineargradient(spread:pad, x1:1, y1:0.682, x2:1, y2:0, stop:0.142857 rgba(220, 0, 22, 255), stop:0.980296 rgba(216, 74, 73, 255), stop:1 rgba(217, 73, 73, 255)); border:none; color:white;");
        b->setText(btnlst[i]);
        if(mood=="Frame")
        {
            QSize size(55,55);
            b->setMinimumSize(size);
            b->setMaximumSize(size);
            b->setSizePolicy(QSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum));
            ui->gridLayout->addWidget(b,0,i,Qt::AlignVCenter);
        }
        else
        {
            QSize size(70,70);
            b->setMinimumSize(size);
            b->setMaximumSize(size);
            b->setSizePolicy(QSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum));
            if(i<4)
                ui->gridLayout->addWidget(b,0,i,Qt::AlignVCenter);
            else
              ui->gridLayout->addWidget(b,0,i-3,Qt::AlignVCenter);
        }

        connect(b,SIGNAL(clicked()),this,SLOT(Function()));
        btn << b;

    }
    ui->gridLayout->setSpacing(0);  

To maintain consistency in appearance, I have set the widget's size to a maximum of 750x150 and a minimum of 600x150. Below are images illustrating my widget layout (utilizing vertical alignment) as well as the result displayed on an embedded device:
https://i.sstatic.net/0aFJu.jpg
https://i.sstatic.net/OCvLP.jpg
While the desired black color for the widget and white color for the group box are achieved, there are unwanted gaps between each button. Additionally, only 5 out of the 8 created buttons are visible within the frame. How can I reduce the spacing between buttons?

Answer №1

To align the layout, you can easily do so by using the layout->setAlignment(...) method. Below is a functional example of center alignment. For other alignments like Qt::AlignRight or Qt::AlignLeft, you can modify accordingly.

#include <QApplication>
#include <QGroupBox>
#include <QLayout>
#include <QPushButton>

class MyWidget : public QGroupBox
{
    Q_OBJECT
public:
    MyWidget(QWidget *parent = 0) : QGroupBox(parent)
    {
        setTitle("GROUP BOX");
        setStyleSheet("QPushButton{background-color: qlineargradient(spread:pad, x1:1, y1:0.682,"
                      "x2:1, y2:0, stop:0.142857 rgba(220, 0, 22, 255),"
                      "stop:0.980296 rgba(216, 74, 73, 255),"
                      "stop:1 rgba(217, 73, 73, 255));"
                      "border:none; color:white;}");
        QGridLayout *grid_layout = new QGridLayout;
        for(int i = 0; i < 5; i++)
        {
            QPushButton *button = new QPushButton;
            button->setFixedSize(80, 80);
            button->setText("Button");
            grid_layout->addWidget(button, 0, i);
        }
        grid_layout->setAlignment(Qt::AlignCenter);
        grid_layout->setSpacing(1);
        setLayout(grid_layout);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MyWidget widget;
    widget.resize(800, 200);
    widget.show();
    return a.exec();
}

#include "main.moc"

Here is the visual result after applying the above code: https://i.sstatic.net/Z3mrT.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a `div` element that transforms into a box when hovered over and displays text

Sorry for repeating a common question, but I'm struggling with CSS and need some help. I am new to this, so any assistance is greatly appreciated. I want to display 14 "element boxes" each with their own background, etc. When hovered over, I would li ...

Enhancing Images with Dynamic Captions Using JQuery

I have created a code to add image captions to different div blocks, and it works as intended. However, I am looking for ways to optimize the code and make it shorter. If you have any advice on how to improve it, please let me know! Thank you in advance. ...

Error message encountered in Python: AttributeError stating that the 'List' object does not possess the attribute 'click'. This error occurred while using Selenium. (Image attached for reference)

Help needed! I am struggling to select an item within the table cell. Below is the source code: <div class="clear formrow top_border"> <div> <table class="infoGrid" cellspacing="0" cellpadding="0" border="0" id="ctl00_cphMain_gd ...

Capturing both the display and audio input devices

Currently, I am developing a C++ program on Windows that needs to be compatible with Windows Vista and later versions. My goal is to simultaneously record both the microphone input and speaker output. While I am able to individually record from the micro ...

Guidelines for retrieving a class name using jQuery when hovering over a div

I need assistance in fetching the class name by hovering over a div. Both divs have the same id but slightly different class names. Here is an example: <div id="1-someid" class="1-example-class border cz"> ...more elements go here.... </div> ...

I'm having trouble with my footer hiding my main content whenever I adjust the screen size. What could be causing

Welcome to my first website! I'm just starting out and trying to figure things out. Despite my best efforts of searching online, I can't seem to find the solution to my issue. I've been tinkering with positioning and containers, but I can&a ...

Is CSS unit pt recommended for styling UI elements?

Currently developing UI controls and deliberating whether to utilize pt for dimensions like widths, heights, border sizes, margins, paddings, and font sizes. Preference is for resizable controls that maintain consistency across various screens and projecto ...

Tips for Embedding External JavaScript and URLs in Joomla Protostar Template

I'm interested in incorporating a hamburger menu into my Joomla protostar template, similar to the one featured on this URL: ['https://codepen.io/PaulVanO/pen/GgGeyE'] This will provide me with a fullscreen hamburger menu for both desktop ...

Using `std::views::split` with Microsoft Visual Studio on Windows

I am looking to split a string using the std::views::split function and then apply the std::from_chars function to each resulting substring. I have provided a minimal reproducible example () that compiles successfully on GCC but encounters compilation erro ...

What is the significance of using CRTP in this particular scenario?

Take a look at the Object counter instance here: Is there a reason it does not simply inherit from non-template class counter? Why does counter need to be templated? template <typename T> struct counter ...

Adjust the opacity of a div as you scroll using jQuery

Check out my code snippet: http://jsfiddle.net/spadez/Fq5K4/ I am looking to create a cool effect where the image in the top section gradually turns black as the user continues scrolling down the page, until it is completely black. This example showcases ...

Access a floating-point value from a MongoDB database using C++

My code deals with retrieving a floating point value named test from a collection in a MongoDB database. However, I'm unsure of the correct method to access this data. It's important to note that I am able to retrieve the name field using the fol ...

Implementing a C Interface to utilize the power of Boost's backend functionality

As I delve into developing a C++ library, the issue of compatibility within its own API and ABI has been on my mind. A helpful resource I came across was this discussion on Creating Library with backward compatible ABI that uses Boost. One of the challeng ...

The issue of CSS3 list navigation not aligning to the left side

While following a tutorial on tuts+ premium, I encountered an issue when the series creator failed to include an exercise file. Despite copying everything from the tutorial video into a CSS document accurately, the CSS list items simply would not float lef ...

Adding extra space around the painter: QPainter

Is there a simple method to include padding in a QPainter area? I want to create a border within the drawable region where drawing is restricted, so that when I draw a line from (0, 0) to (10, 10), I'm actually drawing from (0 + padding, 0 + padding) ...

Automatically changing the page's background color through animation upon loading

Similar Question: jQuery animate backgroundColor Can I make the background-color of a specific element change gradually when the page loads? I have a webpage with content like this: <ul> <li> Some stuff</li> <li> Some ...

Enhancing the Appearance of Multilevel Dropdown Menus

Creating a navigation bar with a multilevel dropdown on it is giving me trouble. I can easily style the text when hovering over my navbar, but styling the insides of the dropdown seems to be a challenge. I've attempted to style it myself without succe ...

Unable to compile avahi4j: avahi4j_Client.c is encountering an issue at line 18, indicating a fatal error due to the absence of avahi-common/error.h file in

Trying to compile avahi4j after downloading from this link, but encountering an error when running ant clean all: ant clean all Buildfile: /home/myUser/Downloads/avahi4j-0.1/build.xml clean: [exec] make: Entering directory `/home/myUser/Downloads/av ...

Fluid Bootstrap layout with a fixed sidebar width

My website has a responsive design based on Twitter's Bootstrap framework. <div class="container-fluid"> <div class="row-fluid"> <div class="span2"> <!--Sidebar content--> </div> <d ...

Performing a dynamic animation by toggling the class of an element with "classList.toggle" in JavaScript

I have been attempting to incorporate a fade animation using CSS when altering the class of the input and label elements within a form by utilizing the classList.toggle method in JavaScript. I'm puzzled as to why my code isn't producing the desir ...