I want to create a custom toolbar widget (something like a ribbon). Then I want to create a QMainWindow
that uses this custom widget as its toolbar.
I can do something like
class RibbonToolbar : public QToolBar {
...
};
...
QMainWindow *window = new QMainWindow();
RibbonToolbar *toolbar = new RibbonToolbar(window);
window->addToolBar(toolbar);
The problem is that in this way RibbonToolbar
inherits all methods from QToolbar
and I don't want it because my widget does not use them. It's a completely new widget.
I'd like to do this:
class RibbonToolbar : public QWidget {
...
};
So if I declare my class in this way, what's the best way to add it to the top of the QMainWindow?
PS: My widget can be adapted if QMainWindow
is resized but, like the ribbon in Microsoft Office, it's a fixed position so it can't move around into the main window.
In C++
, it is not possible to remove functionality from a class. However, it is possible to hide existing functionality. (1)
That being said, how about you hide QToolBar
member functions that you don't want to use by declaring them private
?
Let's use a QWidget
as an example:
widget.h:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
void setGeometry(const QRect &);
void setGeometry(int x, int y, int w, int h);
};
#endif // WIDGET_H
widget.cpp:
#include "widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
}
Widget::~Widget()
{
}
void Widget::setGeometry(const QRect &)
{
}
void Widget::setGeometry(int x, int y, int w, int h)
{
}
In this case, even though setGeometry
is a member function of QWidget
, you can't use it in anymore from Widget
. Similarly you could hide QToolBar::isMovable
by declaring it private and provide an empty implementation for it.
Also more conveniently would be to declare them protected
so that they will be accessible from derived classes if you want.
AFAIK you can't use
class RibbonToolbar : public QWidget {
...
};
because QMainWindow
API is made in such way that it will accept only pointers to QToolBar
for its toolbar areas. You could trick it by creating a RibbonToolbar
which is binary compatible with QToolBar
and reinterpret_cast
the object to QToolBar*
but then you would need to deeply know the inner guts of Qt
and it would still be bad practice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.