Summary: I wish to use X11 to paint a custom QWidget. It works unless that widget is in a layout or QMainWindow
I have a custom widget derived from QWidget that I'd like to be the main widget in a QMainWindow. When I run something like this:
int main(int argc, char** argv) {
QApplication app(argc, argv);
ModelWidget mw;
mw.show();
return app.exec();
}
everything works fine, including resizing, obscuring and revealing the window contents, etc.
However, if I try to use that widget as the central widget in a QMainWindow, nothing is painted in the central widget area of the QMainWindow.
Here's the constructor of the QMainWindow:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
modelwidg = new ModelWidget;
setCentralWidget(modelwidg);
createActions();
createMenus();
}
I get the feeling that there's something related to the size or resize policy of my custom widget that I need to implement, but I can't find any documentation regarding what functions must be provided by a widget for it to be usable as a central widget in a QMainWindow. What am I missing?
Edit: Here's the custom widget
ModelWidget::ModelWidget(QWidget *parent) :
QWidget(parent)
{
setAttribute(Qt::WA_PaintOnScreen);
setAttribute(Qt::WA_NoSystemBackground);
setAttribute(Qt::WA_OpaquePaintEvent);
setAttribute(Qt::WA_NativeWindow);
setAutoFillBackground(true);
const QX11Info &info = x11Info();
// Elided X11 and glX specific stuff
create(wnd, true, true);
}
void ModelWidget::paintEvent(QPaintEvent *)
{
// scene.render is just some OpenGL stuff
scene->render();
glXSwapBuffers(dpy, glxwnd);
}
void ModelWidget::resizeEvent(QResizeEvent * e)
{
glViewport(0, 0, e->size().width(), e->size().height());
scene->set_aspect(float(e->size().width()) / float(e->size().height()));
update();
}
QSize ModelWidget::sizeHint() const
{
return QSize(640, 480);
}
Further...
According to the docs,
To render outside of Qt's paint system, e.g., if you require native
painting primitives, you need to reimplement QWidget::paintEngine() to
return 0 and set [Qt::WA_PaintOnScreen].
I've done that, but the window still remains unpainted. I suspect that one of my X11 objects, Window, Display*, is being altered by adding this widget to a layout or MainWindow.
Related
I've written a simple "proxy widget" class in Qt; the idea is that this widget will hold a single child QWidget and represent that widget in the QWidget hierarchy. (FWIW, the motivation for doing this is to make it easy to move the child widget around the hierarchy without having to directly disturb the state of various other container-QWidgets to do so).
This seems to work fairly well; the only problem I've run into is that I want my ProxyWidget to always be laid-out the same way as its child-QWidget would be (if the child had been added to the widget hierarchy directly); but instead I find that the ProxyWidget is often sized larger than its child would be, leading to wasted space in the GUI.
Therefore, is there some way I can craft my ProxyWidget class so that Qt's layout managers to move/size it exactly the same as if its child widget was added directly?
As a minimal test/example, you can compile the following code and run it with or without the "proxy" command line argument -- my goal is that the visual results would be the same either way, and in particular that you would never see any red pixels in the window (since red pixels indicate areas where the ProxyWidget has been sized larger than the blue child widget it contains)
#include <QApplication>
#include <QStackedLayout>
#include <QWidget>
class ProxyWidget : public QWidget
{
public:
ProxyWidget(QWidget * childWidget)
: _childWidget(childWidget)
, _layout(new QStackedLayout(this))
{
_layout->addWidget(childWidget);
setSizePolicy(childWidget->sizePolicy());
}
virtual QSize sizeHint() const {return _childWidget->sizeHint();}
virtual QSize minimumSizeHint() const {return _childWidget->minimumSizeHint();}
private:
QWidget * _childWidget;
QStackedLayout * _layout;
};
static void SetWidgetBackgroundColor(QWidget * w, const QColor bc)
{
QPalette p = w->palette();
p.setColor(QPalette::Window, bc);
w->setAutoFillBackground(true);
w->setPalette(p);
}
int main(int argc, char ** argv)
{
QApplication app(argc, argv);
QWidget * win = new QWidget;
win->setWindowTitle("Proxy Widget test");
QWidget * proxyMe = new QWidget;
proxyMe->setFixedSize(100, 50);
SetWidgetBackgroundColor(proxyMe, Qt::blue);
QBoxLayout * winLayout = new QBoxLayout(QBoxLayout::TopToBottom, win);
if ((argc >= 2)&&(strcmp(argv[1], "proxy") == 0))
{
ProxyWidget * proxyWidget = new ProxyWidget(proxyMe);
SetWidgetBackgroundColor(proxyWidget, Qt::red);
winLayout->addWidget(proxyWidget);
}
else winLayout->addWidget(proxyMe);
win->show();
return app.exec();
}
I guess minimumSize and maximumSize of ProxyWidget is different from its child widget and setting them fix things in your particular example :
ProxyWidget(QWidget * childWidget)
: _childWidget(childWidget)
, _layout(new QStackedLayout(this))
{
_layout->addWidget(childWidget);
setSizePolicy(childWidget->sizePolicy());
this->setMinimumSize(childWidget->minimumSize());
this->setMaximumSize(childWidget->maximumSize());
}
However i am not sure it's the best solution but it might gives you a hint to a better one.
I am trying to make a child widget to be aligned to the right-bottom corner of a parent widget. The repainting of the child widget is costly so I want to avoid it. Because I am only moving the child widget with a static content, theoretically no repainting is necessary. But I do not know how to achieve that. I react to resizeEvent(), in which I update the child's position to the corner. I have set the widget attributes (trial-error method) to minimize the paint events as far as I was able to. But there are still some repaint events called for the child when the parent is being resized - when enlarged and shrinked as well. When being resized slowly and only in one direction (x or y), it seems only 1 pixel wide band is repainted. When resized faster and in both directions at the same time, the child widget is repainted all. Is it possible to tweak the code to avoid the repainting of the child widget completely? I would like to avoid write manual double-buffering algorithm for this case myself, I hope Qt is able to solve this somehow for me. Is it?
#include <QApplication>
#include <QDebug>
#include <QPainter>
#include <QPaintEvent>
#include <QWidget>
class ChildWidget : public QWidget
{
public:
ChildWidget(QWidget *parent) : QWidget(parent)
{
setAttribute(Qt::WA_StaticContents);
setAttribute(Qt::WA_OpaquePaintEvent);
}
protected:
void paintEvent(QPaintEvent *event) override
{
qDebug() << "paintEvent" << event->rect();
QPainter painter(this);
painter.fillRect(event->rect(), QBrush(QColor("red")));
}
};
class ParentWidget : public QWidget
{
public:
ParentWidget()
{
m_childWidget = new ChildWidget(this);
m_childWidget->resize(100, 100);
setAttribute(Qt::WA_StaticContents);
resize(200, 200);
}
protected:
void resizeEvent(QResizeEvent *event) override
{
QWidget::resizeEvent(event);
m_childWidget->move(width() - 100, height() - 100);
}
private:
ChildWidget *m_childWidget;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ParentWidget w;
w.show();
return a.exec();
}
Note: In my final use case, this parent widget is intended to be covered completely by several non-overlapping child widgets and each of these child widgets will be opaque and will take care of painting its whole area. I.e. no special handling of alpha channel is needed. This might be important information for setting the widget attributes.
Note: I tried a trick, not moving the child immediately, but postpone it with QTimer::singleShot(0, [this]{m_childWidget->move(width() - 100, height() - 100);}); This prevents repainting during parent widget resizing but only in cases when the size of the parent grows. When it shrinks, it is the same as before.
What I was hoping to do was have a standard QMainWindow class with menus, toolbar, plus various widgets in a layout, one of which would be a graphics view showing a graphics widget that contained a graphics layout. But whenever I put the graphics view into a main window nothing gets displayed. If I create my graphics view with the graphics widget containing a layout inside the main() function, then everything is visible.
As a test I took the working code provided in the Qt Basic Graphics Layouts Example, created a QMainWindow class in main, and moved the QGraphicsScene, Window and QGraphicsView creation to the main window class.
I tested the main window class on its own, and widgets like a line edit show up fine. But the code below, taken from main in the example, no longer works when in the main window class.
QGraphicsScene scene;
Window *window = new Window;
scene.addItem(window);
QGraphicsView view(&scene);
view.resize(600, 600);
view.show();
I just get a blank area. If I don't add the Window widget, but instead, for example, draw an ellipse then that is visible. If I add a plain QGraphicsWidget with a background colour then that is also visible. It is just when things are inside a layout on a graphics widget that I get nothing. I've been searching for answers, digging into the documentation and even looking through the Qt source to see if I can figure out if what I am trying to do is even possible, but without any luck.
My main window:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QGraphicsScene scene;
Window *window = new Window;
window->resize(600, 600);
scene.addItem(window);
QGraphicsView view(&scene);
view.resize(600, 600);
view.show();
setCentralWidget(&view);
resize(600,600);
}
Code in main:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow w;
w.show();
return app.exec();
}
One problem is here:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
[...]
QGraphicsView view(&scene);
view.resize(600, 600);
view.show();
[...]
}
You've declared the view widget on the stack, which means it will be automatically destroyed as soon as your MainWindow constructor returns, and thus the user will never see it. What you should do instead is something like this:
QGraphicsView * view = new QGraphicsView(&scene, this);
view->resize(600, 600);
view->show();
You'll have a similar problem with your QGraphicsScene object:
QGraphicsScene scene;
... since it is also declared as a local variable inside the constructor-method, it will also be destroyed when the constructor-method returns, leaving you with no scene. I suggest making it a class-member variable instead; that way it will last as long as your MainWindow does.
(Note that declaring items on the stack worked in the example-program you copied from, only because they were declared in the directly in the main() method, and main() doesn't return until the program is ready to exit... thus the objects in the example program would not be destroyed until the program was exiting anyway)
I am trying to create a MDI document program. I have a question on creating the subwindow.
This is my mainwindow constructor:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle(tr("MDI"));
workspace = new QMdiArea;
setCentralWidget(workspace);
//fileNew();
createActions();
createMenus();
createToolbars();
statusBar()->showMessage(tr("Done"));
enableActions();
}
The interesting point is the fileNew(); function. It is a private slot function actually which I want to invoke when "New File" button is triggered. Here is the private slot fileNew() function:
void MainWindow::fileNew()
{
DocumentWindows* document = new DocumentWindows;
workspace->addSubWindow(document);
}
This function works perfectly when I call from the mainwindow constructor. However, there is a problem when I call it from the createActions(); function which uses a signal-slot mechanism.
Here is my createActions()
void MainWindow::createActions()
{
newAction = new QAction(QIcon(":/Image/NewFile.png"),tr("&New"),this);
newAction->setShortcut(tr("Ctrl+N"));
newAction->setToolTip(tr("Open new document"));
connect(newAction, SIGNAL(triggered(bool)), this, SLOT(fileNew()));
}
No subwindow is created even the SLOT is triggered. Subsequently, I find out that if I add document->show();, everything works well.
void MainWindow::fileNew()
{
DocumentWindows* document = new DocumentWindows;
workspace->addSubWindow(document);
document->show();
}
My question is: Why the show() function is needed in a SLOT but not in the constructor?
PS. DocumentWindows is just a class inherits QTextEdit.
This problem has nothing to do with the class of the widgets one is using. It is unrelated to documents, MDI, or the main window. After you add a child widget to a widget that is already visible, you must explicitly show it. Otherwise, the widget will remain hidden.
All widgets are hidden by default. When you initially show the MainWindow, all of its children are recursively shown too. When you later add a child MDI widget, it remains hidden. When widgets are added to layouts, they are shown by default - but your widget is managed by the MDI area, not by a layout.
This is a minimal test case demonstrating your issue:
// https://github.com/KubaO/stackoverflown/tree/master/questions/widget-show-32534931
#include <QtWidgets>
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QWidget w;
w.setMinimumSize(200, 50);
QLabel visible{"Visible", &w};
w.show();
QLabel invisible{"Invisible", &w};
invisible.move(100, 0);
return app.exec();
}
I have a custom widget, which inherits QWidget. It has own paintEvent and I cannot change it. So I want to use such a widget in my dialog object, but I need to draw some graphics on it after it draws its own graphics (that widget draws video frames on it, an I need to draw some lines over it). Can I draw every time after the paintEvent of that widget? I used installEventFilter and caught the event wuth type Qt::Paint, but I canoont see anything I've drown. Is there any other way?
You can derive from the custom widget class, reimplement paintEvent, and call the inherited paintEvent first, then do your drawing.
You can install an event filter on the widget and do the same: call the widget's paintEvent first, then do your drawing.
Hide the other widget. Create your own widget, and call the other widget's render method in your widget's paintEvent, then do your drawing. Since the other widget is presumably rendering video frames that change periodically over time, you might need to use a timer to update() your widget.
In neither case are you modifying the 3rd party custom widget.
In order to call other widget's protected paintEvent you need to be using a QWidget, even if just a dummy, invisible one.
This is a very simple code sample that draw inside a custom widget. It draws a blue rectangle inside of a QPushButton.
The method used is exactly what has been described in option 1 by #Kuba
So, you inherit from the custom widget class where you want to draw in, reimplement paintEvent, and call the inherited paintEvent first and the do your drawing.
Hope this helps
#include <QApplication>
#include <QPushButton>
#include <QPainter>
#include <QPaintEvent>
// inherit from the class over which you want to draw
class DrawOverButton : public QPushButton
{
Q_OBJECT
public:
DrawOverButton(const QString &text, QWidget *parent = 0) :
QPushButton(text, parent)
{
// enlarge the button so there is some space to draw in
setStyleSheet("QPushButton {min-height: 60px; "
"min-width: 120px; margin: 5px;}");
}
protected:
virtual void paintEvent(QPaintEvent *event) {
// call the base class paint event method
// this will draw the base class content
QPushButton::paintEvent(event);
// draw a blue border inside the button
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(QColor("#3cf"), 4));
const int distance = 20;
painter.drawRoundedRect(QRect(distance, distance,
width() - 2 * distance, height() - 2 * distance),
10, 10);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
DrawOverButton *button = new DrawOverButton("Button");
button->show();
return a.exec();
}
#include "main.moc"