1

I'm new to qt and exploring it .I want to have a text which is center aligned in my Mainwindow's toolbar.Below is my code inside my MainWindow constructor:

QLabel* label=new QLabel("Hello World");
label->setAlignment(Qt::AlignHCenter);

QHBoxLayout *layout = new QHBoxLayout();
layout->addWidget(label);

QWidget* wid = new QWidget;
wid->setLayout(layout);

ui->mainToolBar->addWidget(wid);

The above code displays the text , but not at the center.It displays at the left.What am I missing?Any help will be really helpful.

george
  • 339
  • 3
  • 12

1 Answers1

3
label->setAlignment(Qt::AlignHCenter);

This tells the label to (horizontally) center the text in itself.

layout->addWidget(label);

This is expanded by default argument to

layout->addWidget(label, 0);

Where the 0 is the stretch factor of the label within this layout. Zero means your label will be given as much space as it needs to display properly but nothing more. So your label is just as big as your text needs, has it's text centered, but since it's on a QHBoxLayout it's shown on the left side within your bar. If there are no other widgets in your bar's layout, you can set the stretch-factor to 1 to make the label fill the layout, your text will then show in the center.

layout->addWidget(label, 1);
markus-nm
  • 805
  • 5
  • 8
  • Thank u man!..Its working..Im trying to develop a qt desktop app which works independent of resolution..could u suggest me some idea?? – george Jul 04 '18 at 13:18
  • Qt has all you need for screen-independent interfaces. Make sure to use the latest Qt-Versions available. Try to make as few as possible constant-sized widgets/layouts; use layouts with stretch- or size-factors whereever possible, so all interface elements can scale with screen-size/resolution. Have all image-resources available in high and low resolution (or just high resolution and then downscale-to-fit at runtime). – markus-nm Jul 04 '18 at 13:37
  • Thanks man,I see a dotted button sort of thing to the left of the toolbar and right clicking it gives a checkbox to hide the toolbar.Is der a way to remove that dotted button? – george Jul 04 '18 at 13:55
  • I assume you loaded one of the example projects? Anyway, if there's a button, theres bound to be some code in your project (or some line in your .ui files) that define this button. remove them and your button is gone. – markus-nm Jul 04 '18 at 14:06
  • Hi markus.. my layout has only default qt toolbar .no other button apart from my central widget..Im able to remove the entire toolbar,but I dont want that.Is der any work around to remove that dotted component? – george Jul 05 '18 at 07:38