×
Namespaces

Variants
Actions

Archived:How to overlay QWidget on top of another

From Nokia Developer Wiki
Jump to: navigation, search

Archived.pngArchived: This article is archived because it is not considered relevant for third-party developers creating commercial solutions today. If you think this article is still relevant, let us know by adding the template {{ReviewForRemovalFromArchive|user=~~~~|write your reason here}}.

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.

WidgetOverlayedOnTopOfTextAreaCapture.JPG
Article Metadata
Code ExampleTested with
Devices(s): Emulator / desktop / device
Compatibility
Platform(s): All Qt Supported
Symbian
Article
Keywords: QWidget
Created: skumar_rao (25 Nov 2010)
Last edited: hamishwillee (11 Oct 2012)

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)

This page was last modified on 11 October 2012, at 04:14.
340 page views in the last 30 days.