Archived:How to overlay QWidget on top of another
Qt Quick should be used for all UI development on mobile devices. The approach described in this article (using C++ for the Qt app UI) is deprecated.
This article demonstrates how to overlap one QWidget on top of another.
Article Metadata
Code Example
Tested with
Compatibility
Article
Basic Idea
Let us create an overlay widget, this is just a simple widget with transparent background and Its QPainter::setRenderHint is set to QPainter::Antialiasing.
Overlay.h
class Overlay : public QWidget
{
public:
Overlay(QWidget *parent);
protected:
void paintEvent(QPaintEvent *event);
};
Overlay.cpp
Overlay::Overlay(QWidget *parent) :QWidget(parent) {
setPalette(Qt::transparent);
setAttribute(Qt::WA_TransparentForMouseEvents);
}
void Overlay::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(QPen(Qt::red));
painter.drawLine(width()/8, height()/8, 7*width()/8, 7*height()/8);
painter.drawLine(width()/8, 7*height()/8, 7*width()/8, height()/8);
}
in mainwindow class Once we have set the central widget, we construct an instance of our Overlay widget and set central widget as its parent. This causes it to exist as a child of the standard widgets, but it is not managed by the layout. So, we need to ensure that it is resized whenever the main window resizes, for that reason we reimplemented the main window's resizeEvent() handler.
mainwindow.h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
void resizeEvent(QResizeEvent *event);
private:
Overlay *overlay;
};
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent) {
QWidget *widget = new QWidget();
QTextEdit *editor = new QTextEdit();
QGridLayout *layout = new QGridLayout(widget);
layout->addWidget(editor, 0, 0, 1, 2);
setCentralWidget(widget);
overlay = new Overlay(centralWidget());
}
MainWindow::~MainWindow() {
}
void MainWindow::resizeEvent(QResizeEvent *event) {
overlay->resize(event->size());
event->accept();
}
Note the same can be done to show any graphics on top of any control
Example code File:TestOverlay.zip
--skumar_rao 17:56, 25 November 2010 (UTC)


(no comments yet)