Qt menubar not showing - c++

I'm building a simple C++ application on Mac OS X 10.9 with Qt 5.2.1 using CMake (without MOC).
I am starting the executable from the command-line. The problem is that the menu bar is not showing up at all, the Terminal menu bar is still visible but not clickable. When I switch windows temporarily and then come back to the window of this application, I at least see the standard "application" menu with "About". The "About" action is now working and shows the dialog. The toolbar button also works as expected.
What else I tried (and didn't work):
using the pre-defined menuBar()
use setMenuBar()
new menuBar(0)
menubar->setVisible(true)
When I check the isVisible() it returns false, also if I set it to visible in the line before.
I wonder whether the lack of using MOC can be the reason for this?
Below I attached a reduced example.
#include <QtGui>
#include <QtWidgets>
class MainWindow : public QMainWindow {
public:
MainWindow();
private:
void create_actions_();
void create_menus_();
void create_toolbar_();
void about_();
QMenuBar* menu_bar_;
QMenu* file_menu_;
QMenu* help_menu_;
QToolBar* file_toolbar_;
QAction* action_about_;
};
MainWindow::MainWindow() {
resize(800, 600);
create_actions_();
create_menus_();
create_toolbar_();
}
void MainWindow::create_actions_() {
action_about_ = new QAction(tr("About"), this);
connect(action_about_, &QAction::triggered, this, &MainWindow::about_);
}
void MainWindow::create_menus_() {
menu_bar_ = new QMenuBar(this);
file_menu_ = menu_bar_->addMenu(tr("&File"));
menu_bar_->addSeparator();
help_menu_ = menu_bar_->addMenu(tr("&Help"));
help_menu_->addAction(action_about_);
menu_bar_->setNativeMenuBar(true);
}
void MainWindow::create_toolbar_() {
file_toolbar_ = addToolBar(tr("File"));
file_toolbar_->addAction(action_about_);
file_toolbar_->setIconSize(QSize(16, 16));
}
void MainWindow::about_() {
QMessageBox::about(this, tr("About"), tr("FooBar"));
}
int main(int argc, char **argv) {
QApplication app(argc, argv);
MainWindow main_window;
main_window.show();
const int exit_code = app.exec();
return exit_code;
}
CMakeLists.txt
FIND_PACKAGE(Qt5Core)
FIND_PACKAGE(Qt5Gui)
FIND_PACKAGE(Qt5OpenGL)
FIND_PACKAGE(Qt5Widgets)
FIND_PACKAGE(Qt5Declarative)
FIND_PACKAGE(Qt5MacExtras)
ADD_EXECUTABLE(main main.cc)
qt5_use_modules(main Core Gui Widgets Declarative MacExtras)
Thanks a lot in advance!

OK, solved the problem myself. It appears you cannot add a separator to the menubar.
Removing the menu_bar_->addSeparator(); solved the problem.

Related

QPushButton not executing connected function on click

I have a class called UserInterface. In this class there are different functions. build_start_screen() adds all the widgets (labels, buttons,...) for the initial startscreen. build_option_a_screen() removes everything from the startscreen and adds all the widgets needed for the screen when the users click on the button for option A, and so on. The class is stripped down for the sake of this question.
Now I have declared a button in build_start_screen() and connected it to a simple MessageBox.exec() so it should pop-up on click.
However, nothing happens when the button gets clicked.
What am I doing wrong? Has it something to do with the lifetime of variables expiring after the function finishes?
#include <QApplication>
#include <QPushButton>
#include <QAbstractButton>
#include <QLabel>
#include <QFont>
#include <QVBoxLayout>
#include <QMessageBox>
//Class handling all the UI in this Application
class UserInterface {
public:
//Build the initial UI the user sees
void build_start_screen(QWidget& window) {
//Make new QVBoxLayout for this startscreen UI
this->layout = new QVBoxLayout(&window);
//Test messagebox
QMessageBox msgBox;
msgBox.setText("Button test.");
//Button to go to Option A-screen
QPushButton* showMsgBox = new QPushButton("Show pop-up");
QAbstractButton::connect(showMsgBox, SIGNAL (clicked()), &window, SLOT (msgBox.exec()));
//Add labels and button to QVBoxLayout
layout->addWidget(showMsgBox);
}
private:
//Properties
QVBoxLayout* layout;
};
int main(int argc, char **argv) {
QApplication app (argc, argv);
//Initialize Window
QWidget Window;
Window.resize(400, 250);
//Create new UserInterface object
//This will allow us to create different user-interfaces
//depending on the function we call
UserInterface* ui = new UserInterface();
ui->build_start_screen(Window);
Window.show();
return app.exec();
}
And what if I'd like to do the same, but instead of calling a messageBox I'd like to call another function?
#include <QApplication>
#include <QPushButton>
#include <QAbstractButton>
#include <QLabel>
#include <QFont>
#include <QVBoxLayout>
#include <QMessageBox>
//Class handling all the UI in this Application
class UserInterface {
public:
//Build the initial UI the user sees
void build_start_screen(QWidget& window) {
//Make new QVBoxLayout for this startscreen UI
this->layout = new QVBoxLayout(&window);
//Test messagebox
QMessageBox msgBox;
msgBox.setText("Button test.");
//Button to go to Option A-screen
QPushButton* showMsgBox = new QPushButton("Show pop-up");
QAbstractButton::connect(showMsgBox, SIGNAL (clicked()), &window, SLOT (build_option_a_screen()));
//Add labels and button to QVBoxLayout
layout->addWidget(showMsgBox);
}
void build_option_a_screen(QWidget& window) {
//Do stuff here with window
//e.g
window.resize(500, 500);
}
private:
//Properties
QVBoxLayout* layout;
};
int main(int argc, char **argv) {
QApplication app (argc, argv);
//Initialize Window
QWidget Window;
Window.resize(400, 250);
//Create new UserInterface object
//This will allow us to create different user-interfaces
//depending on the function we call
UserInterface* ui = new UserInterface();
ui->build_start_screen(Window);
Window.show();
return app.exec();
}
Your code has 2 problems:
The window "object" does not have slot "msgBox.exec()" as pointed out by the error:
QObject::connect: No such slot QWidget::msgBox.exec() in ../main.cpp:23
Correcting the above, the solution would be:
QObject::connect(showMsgBox, &QPushButton::clicked, &msgBox, &QMessageBox::exec);
but now the problem is that "msgBox" is a local variable that will be destroyed and cannot be displayed.
So the solution is to make msgBox a member of the class or a pointer (in the case of the pointer you must manage the dynamic memory to avoid memory leaks):
//Class handling all the UI in this Application
class UserInterface {
public:
//Build the initial UI the user sees
void build_start_screen(QWidget& window) {
//Make new QVBoxLayout for this startscreen UI
this->layout = new QVBoxLayout(&window);
msgBox.setText("Button test.");
//Button to go to Option A-screen
QPushButton* showMsgBox = new QPushButton("Show pop-up");
QObject::connect(showMsgBox, &QPushButton::clicked, &msgBox, &QMessageBox::exec);
//Add labels and button to QVBoxLayout
layout->addWidget(showMsgBox);
}
private:
//Properties
QVBoxLayout* layout;
QMessageBox msgBox;
};
Plus:
It is recommended not to use the old connection syntax as it has limitations and hides the problems.
It is recommended not to use the old connection syntax as it has limitations and hides the problems.
If you want to connect to a method of some kind that is not a QObject (for example X as you want the OP) then the solution is to use a lambda method:
//Class handling all the UI in this Application
class UserInterface {
public:
//Build the initial UI the user sees
void build_start_screen(QWidget& window) {
//Make new QVBoxLayout for this startscreen UI
this->layout = new QVBoxLayout(&window);
//Button to go to Option A-screen
QPushButton* showMsgBox = new QPushButton("Show pop-up");
QObject::connect(showMsgBox, &QPushButton::clicked, [this, &window](){
build_option_a_screen(window);
});
//Add labels and button to QVBoxLayout
layout->addWidget(showMsgBox);
}
void build_option_a_screen(QWidget& window) {
//Do stuff here with window
//e.g
window.resize(500, 500);
}
private:
//Properties
QVBoxLayout* layout;
};

Why am I getting QWindowsWindow::setGeometry: Unable to set geometry warning with Qt 5.12.0

I migrated some code from Qt 5.6.0 to 5.12.0. Suprisingly, I'm getting lots of warnings related to QWindowsWindow::setGeometry. Whenever a dialog is shown on top of another, I get this warning.
I could isolate the problem in a MCVE, it's very simple and minimal, all parenting look good, however, we get the warning when button is pressed:
QWindowsWindow::setGeometry: Unable to set geometry 132x30+682+303 on QWidgetWindow/'QDialogClassWindow'. Resulting geometry: 132x42+682+303 (frame: 4, 28, 4, 4, custom margin: 0, 0, 0, 0, minimum size: 116x42, maximum size: 16777215x16777215).
main.cpp:
#include <QApplication>
#include "mainframe.h"
#include <qDebug>
void MessageOutput( QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
qDebug() << msg;
}
int main( int argc, char* argv[] )
{
QApplication app(argc, argv);
qInstallMessageHandler(MessageOutput);
MainFrame wnd;
wnd.show();
return app.exec();
}
mainframe.h:
#include <QMainWindow>
class QPushButton;
class MainFrame : public QMainWindow
{
Q_OBJECT
public:
MainFrame();
public slots:
void showPopup();
private:
QPushButton* button;
};
mainframe.cpp:
#include "mainframe.h"
#include <QDialog>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
MainFrame::MainFrame()
{
QWidget* widget = new QWidget( this );
widget->setLayout( new QVBoxLayout( widget ) );
QPushButton* pTextButton = new QPushButton( "Show popup", widget );
widget->layout()->addWidget( pTextButton );
connect( pTextButton, SIGNAL(clicked()), this, SLOT(showPopup()) );
setCentralWidget( widget );
}
void MainFrame::showPopup()
{
QDialog dlg( this );
dlg.setLayout( new QVBoxLayout() );
dlg.layout()->addWidget( new QLabel("popup message",&dlg) );
dlg.exec();
}
I see the issue under Windows 7 and 10. Am I doing anything wrong?
I know the warning can be removed by setting setMinimumSize (see https://stackoverflow.com/a/31231069/3336423), but why should we do this for every widget we create? Is there a way to fix that for good?
As you mentioned, this problem occurs only in Windows: the QWindowsWindow class is part of the windows platform plugin. Looking at Qt's source code (qwindowswindow.cpp#QWindowsWindow::setGeometry) there is no direct way to pause that specific message.
The only global solution I can think of right now is to filter the warning messages using a message handler:
void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
if (type != QtWarningMsg || !msg.startsWith("QWindowsWindow::setGeometry")) {
QByteArray localMsg = msg.toLocal8Bit();
fprintf(stdout, localMsg.constData());
}
}
int main(int argc, char* argv[])
{
qInstallMessageHandler(myMessageOutput);
QApplication a(argc, argv);
// ...
}
UPDATE
One of the problems is that Windows adds its own buttons to the frame. In your example the dialog adds three buttons: the system button (the icon, top-left corner), the help button and the close button. The help and close buttons have a fixed size, which happens to be larger than the QDialog's frame (which is computed as the maximum between the requested size and minimumSize). This then generates the warning: your requested size doesn't match the one created by Windows:
If you remove the help button, for example (dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowContextHelpButtonHint);), the warning disappears without setting a minimum size for the window. A manual action must be taken for each dialog displayed, but I think it is easier to automatize than the minimum size (through a factory maybe?):
The issue was reported to Qt:
https://bugreports.qt.io/browse/QTBUG-73258
To the code in OP is OK, it's just a Qt bug.
It's marked as "P2 Important", so hopefully it should be fixed in a next release.
Update: It's still not fixed in Qt 6.2.2...

How do I change qt label text to look like window title text

In my program I am displaying a dialog window to provide information to the user. I am using the QT Label element to do this and I would like to make the text look more "organic" or carved in, like the title text of a window than simple black on gray. Does anyone have any suggestions? I am using QT Creator and coding in c++ for Linux.
here is an image of what I am trying to acomplish
I prepared an MCVE to demonstrate the options I suggested in my comments.
Changing style of QLabel is rather simple and straight forward.
Using the QStylePainter doesn't quite match what I actually expected. I left in the sample code what I got so far. (May be, somebody could leave a helpful hint.) I will investigate in this topic later and edit this answer as soon as I got some satisfying progress on this topic.
The sample code:
#include <QtWidgets>
class TitleBar: public QWidget {
private:
QStyleOptionTitleBar _option;
//QString _text;
public:
explicit TitleBar(
const QString &text = QString(), QWidget *pQParent = nullptr);
protected:
virtual QSize sizeHint() const;
virtual void resizeEvent(QResizeEvent *pQEvent);
virtual void paintEvent(QPaintEvent *pQEvent);
};
int main(int argc, char **argv)
{
qDebug() << "Qt Version: " << QT_VERSION_STR;
// main application
#undef qApp // undef macro qApp out of the way
QApplication qApp(argc, argv);
// setup of GUI
QWidget qWin;
QVBoxLayout qBox;
// a boring label
QLabel qLbl1(QString::fromUtf8("Rather boring"));
qLbl1.setAlignment(Qt::AlignCenter);
qBox.addWidget(&qLbl1);
// a label with frame
QLabel qLbl2(QString::fromUtf8("Label with Frame"));
qLbl2.setFrameStyle(QLabel::Panel | QLabel::Raised);
qLbl2.setLineWidth(2);
qLbl2.setAlignment(Qt::AlignCenter);
qBox.addWidget(&qLbl2);
// a label with rich-text
QLabel qLbl3(
QString::fromUtf8(
"<body bgcolor='#28f'>" // doesn't have the effect
"<font size='+2' color='#f8e' face='Old English Text MT'>"
"Label <i>with</i> <b>Rich-Text</b>"
"</font>"
"</body>")); // background is set by style-sheet instead
qLbl3.setTextFormat(Qt::RichText); // might be auto-detected...
qLbl3.setStyleSheet("QLabel { background-color: #28f; }");
qLbl3.setAlignment(Qt::AlignCenter);
qLbl3.show();
qBox.addWidget(&qLbl3);
// a home-brew title bar
TitleBar qTitle("A Home-Brew Title Bar");
qBox.addWidget(&qTitle);
// finish setup of GUI
qWin.setLayout(&qBox);
qWin.show();
// run application
return qApp.exec();
}
TitleBar::TitleBar(const QString &text, QWidget *pQParent):
QWidget(pQParent)
{
_option.initFrom(this);
_option.titleBarFlags = Qt::Window;
_option.text = text;
}
QSize TitleBar::sizeHint() const
{
#if 0 // does not provide the expected result
return _option.rect.size();
#elif 0 // does not provide the expected result
return style()->proxy()->subControlRect(QStyle::CC_TitleBar,
&_option, QStyle::SC_TitleBarLabel).size();
#else
return QSize(0,
style()->proxy()->pixelMetric(QStyle::PM_TitleBarHeight,
&_option, this));
#endif // 0
}
void TitleBar::resizeEvent(QResizeEvent *pQEvent)
{
_option.rect = QRect(_option.rect.topLeft(), pQEvent->size());
}
void TitleBar::paintEvent(QPaintEvent *pQEvent)
{
QPainter qPainter(this);
style()->proxy()->drawComplexControl(QStyle::CC_TitleBar,
&_option, &qPainter, this);
}
I compiled and tested it in VS2013 on Windows 10 (64 bit). Below a snapshot:

QT 5.3 Mac Full Screen

I'm trying to set my application to full screen and back in Qt 5.3, but I'm running into some issues on Mac. When I use showFullScreen(), it goes into full screen as expected. It uses the standard Mac full screen mode where it opens in a separate desktop/space. However, when I call showNormal() to return from full screen mode, the application window just disappears and I'm left with a gray background. I need to swipe in order to return to the regular desktop where the application is.
Is this a bug in Qt or am I doing something wrong? I'm on OS X 10.9.3.
I had similar problems with Qt 5.2 on Mac OS X (but not Qt 4.8). This seems to fix it:
if ( showFullScreen )
{
widget->setParent( NULL );
widget->showFullScreen();
}
else
{
// changing the order of the showNormal() and setParent() results in a grey screen in Qt 5 on Mac
widget->showNormal();
widget->setParent( widgetParent ); // reset the original parent
}
I am not sure if this or this relate to your problem. But it seems that calls to showFullScreen() and showNormal() is buggy on Mac.
You can change the calls to showFullScreen() and showNormal() with setWindowState().
showFullScreen(); can be changed to
setWindowState(windowState() | Qt::WindowFullScreen);
And showNormal(); can be changed to
setWindowState(windowState() & ~Qt::WindowFullScreen);
Here's a trivial example application that works correctly on my system (Qt 5.3.1, MacOS/X 10.9.5). Does it work correctly for you also? If so, try and figure out what is different between this program and your program.
You might also try calling show(), raise(), and activateWindow() after calling showNormal() and see if those things help.
// MyWindow.h
#ifndef MYWINDOW_H
#define MYWINDOW_H
#include <QAction>
#include <QLabel>
#include <QTimer>
#include <QTime>
#include <QMainWindow>
class MyWindow : public QMainWindow
{
Q_OBJECT
public:
MyWindow();
private slots:
void goFS();
void goNormal();
private:
QAction * fsAct;
QAction * normAct;
};
#endif // MYWINDOW_H
... and the .cpp file:
// MyWindow.cpp
#include <QApplication>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include "MyWindow.h"
MyWindow :: MyWindow()
{
fsAct = new QAction(tr("Full Screen Mode"), this);
connect(fsAct, SIGNAL(triggered()), this, SLOT(goFS()));
normAct = new QAction(tr("Normal Mode"), this);
connect(normAct, SIGNAL(triggered()), this, SLOT(goNormal()));
normAct->setEnabled(false);
QMenuBar * mb = menuBar();
QMenu * modeMenu = mb->addMenu(tr("ScreenMode"));
modeMenu->addAction(fsAct);
modeMenu->addAction(normAct);
}
void MyWindow :: goFS()
{
normAct->setEnabled(true);
fsAct->setEnabled(false);
showFullScreen();
}
void MyWindow :: goNormal()
{
normAct->setEnabled(false);
fsAct->setEnabled(true);
showNormal();
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyWindow scr;
scr.show();
return a.exec();
}

With QToolBox, which setting to have page be only its content size?

I'm trying to find the settings or size policy so that each page in my QToolBox instance only takes up the space needed by its content. I've tried everything I could see in the properties for both the instance and for each of the individual pages.
Am I misconstruing the functionality of QToolBox widget or just missing the right setting?
What I am going for is something similar to the accordion fold type widget in Qt Creator:
I can't seem to get this "Sort" page to take only the size needed to display the button and field.
Unfortunately you can't do that directly because it will span all the available space that the title widgets don't occupy. You can emulate what you want by setting a fixed height on the QToolBox if you know the exact height your page(s). But you do not want to do that in practise.
If you want the behavior you ask for then you need to write your own custom control. It doesn't have to be hard. Use a QVBoxLayout and fill into it items of a custom class, let's call it ToolItem, which is a QWidget with a title (perhaps a button to show/hide) and another QWidget for showing the contents that is either visible or not.
The following very simple example will toggle the visibility of the ToolItem when it is clicked. And only when visible will it occupy any space.
class ToolItem : public QWidget {
public:
ToolItem(const QString &title, QWidget *item) : item(item) {
QVBoxLayout *layout = new QVBoxLayout;
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(new QLabel(title));
layout->addWidget(item);
setLayout(layout);
item->setVisible(false);
}
protected:
void mousePressEvent(QMouseEvent *event) {
item->setVisible(!item->isVisible());
}
private:
QWidget *item;
};
class ToolBox : public QWidget {
public:
ToolBox() : layout(new QVBoxLayout) {
setLayout(layout);
}
void addItem(ToolItem *item) {
// Remove last spacer item if present.
int count = layout->count();
if (count > 1) {
layout->removeItem(layout->itemAt(count - 1));
}
// Add item and make sure it stretches the remaining space.
layout->addWidget(item);
layout->addStretch();
}
private:
QVBoxLayout *layout;
};
And simple usage of it:
QWidget *window = new QWidget;
window->setWindowTitle("QToolBox Example");
QListWidget *list = new QListWidget;
list->addItem("One");
list->addItem("Two");
list->addItem("Three");
ToolBox *toolBox = new ToolBox;
toolBox->addItem(new ToolItem("Title 1", new QLabel("Some text here")));
toolBox->addItem(new ToolItem("Title 2", list));
toolBox->addItem(new ToolItem("Title 3", new QLabel("Lorem Ipsum..")));
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(toolBox);
window->setLayout(layout);
window->resize(500, 500);
window->show();
You can now tweak it to look like the QToolBox if needed.
Please don't hesitate to ask follow-up questions.
The example shown from Qt Designer may not be using a QToolBox, which behaves more like a stacked tab widget only displaying a single page at a time. The example in Qt Designer appears to be a QTreeWidget with custom drawing or styling.
This is not the complete answer.
I traced down the actual component, it can be included outside designer (kind of). Here is a minimal example showing how to do that (modified from https://github.com/zdenekzc/qtdesigner-integration).
form.h
#ifndef FORM_H
#define FORM_H
#include <QMainWindow>
class FormWindow : public QMainWindow {
Q_OBJECT
public:
explicit FormWindow (QWidget * parent = 0);
};
#endif // FORM_H
form.cc
#include "form.h"
#include <QApplication>
#include <QtDesigner/QtDesigner>
#include <QtDesigner/QDesignerComponents>
FormWindow::FormWindow (QWidget* parent) : QMainWindow (parent) {
QDesignerFormEditorInterface* core = QDesignerComponents::createFormEditor (this);
core->setWidgetBox (QDesignerComponents::createWidgetBox (core, 0));
this->setCentralWidget (core->widgetBox());
}
extern "C" int main (int argc, char * * argv) {
QApplication app (argc, argv);
FormWindow * win = new FormWindow ();
win->show ();
return app.exec();
}
qt-designer.pro
QT += designer
HEADERS = form.h
SOURCES = form.cc
LIBS += -lQt5DesignerComponents
Build it:
mkdir -p build
cd build
qmake-qt5 ../qt5-design.pro
make
./qt5-design
This is obviously not useful by itself unless you want to build a designer but another step towards isolating the actual component.