質問

I'm trying to overlap two QLabels. One qlabel contains an image, while the other one draws a rectangle when I tell it to. Both work individually, but I need to overlap the rectangle QLabel on top of the image QLabel. In QMainWindow I only have one option: to setCentralWidget. How would I do this?

役に立ちましたか?

解決

If you want two overlapping labels, you do not add them to a layout but position them directly within their parent window.

something like this:

// ...
parent = new QWidget();
label1 = new QLabel(parent);
label2 = new QLabel(parent);
label1->setGeometry(QRect(100,100,80,20));
label2->setGeometry(QRect(100,100,80,20));
// ...

他のヒント

You can add the bottom label to the layout, but not the top (overlapping) one. Slave the position of the top one to the bottom one. For the bottom label, you'll need to use a class derived from QLabel, where you override resizeEvent(...), emit a signal, and call the inherited QLabel::resizeEvent(...). Connect that signal to a slot in the top label, also a QLabel-derived class. The slot manipulates the received geometry of the bottom label to obtain the geometry of the top one, and calls this->setGeometry(...). Below is an SSCCE.

Output from the example code

#overlap.pro
QT       += core gui
TARGET = overlap
TEMPLATE = app
SOURCES += main.cpp
//main.cpp
#include <QtGui/QLabel>
#include <QHBoxLayout>
#include <QtGui/QApplication>

class TopLabel : public QLabel
{
    Q_OBJECT
public:
    TopLabel(QWidget * parent = 0) : QLabel(parent) {}
    TopLabel(const QString & text, QWidget * parent = 0) : QLabel(text, parent) {}
public slots:
    void bottomGeometry(const QRect & r) {
        setGeometry(r.left() + r.width()*0.25, r.top() + r.height()*0.1,
                    r.width()*0.5, r.height()*0.5);
    }
};

class BottomLabel : public QLabel
{
    Q_OBJECT
public:
    BottomLabel(QWidget * parent = 0) : QLabel(parent) {}
    BottomLabel(const QString & text, QWidget * parent = 0) : QLabel(text, parent) {}
signals:
    void newGeometry(const QRect & r);
protected:
    void resizeEvent(QResizeEvent *) { emit newGeometry(geometry()); }
    void moveEvent(QMoveEvent *) { emit newGeometry(geometry()); }
};

class Window : public QWidget
{
public:
    Window() {
        QLayout * layout = new QHBoxLayout();
        QLabel * l = new QLabel("Left", this);
        l->setFrameStyle(QFrame::Box | QFrame::Raised);
        layout->addWidget(l);
        BottomLabel * bl = new BottomLabel("Right", this);
        bl->setFrameStyle(QFrame::Box | QFrame::Raised);
        TopLabel * tl = new TopLabel("TOP", this);
        tl->setFrameStyle(QFrame::StyledPanel);
        connect(bl, SIGNAL(newGeometry(QRect)), tl, SLOT(bottomGeometry(QRect)));
        layout->addWidget(bl);
        setLayout(layout);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Window w;
    w.show();
    return a.exec();
}

#include "main.moc"
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top