简体   繁体   中英

How to create a draggable (borderless and titleless) top level window in QT

I'd appreciate help creating a top-level window in Qt with the following characteristics. The window must be:

  1. Borderless, titleless and lie on top of all other windows on the desktop (easy)
  2. Draggable by clicking and dragging anywhere inside it (this what I need help with)
  3. Constrained to the top border of the desktop while dragging (relatively easy)

Basically, I'm trying to collapse our QT application to a top-level icon on the top border of the desktop.

You'll find the answer to the first part in: Making a borderless window with for Qt , and the answer to the second part in Select & moving Qwidget in the screen .

Combining the two, and adding the last part is straightforward.

Here's how you could do it:

#include <QtGui>

class W: public QWidget
{
    Q_OBJECT

Set up a borderless widget with a few buttons to lock/unlock and quit:

    public:
        W(QWidget *parent=0)
            : QWidget(parent, Qt::FramelessWindowHint), locked(false)
        {
            QPushButton *lock   = new QPushButton("Lock");
            QPushButton *unlock = new QPushButton("Unlock");
            QPushButton *quit   = new QPushButton("&Quit");

            connect(lock,   SIGNAL(clicked()), this, SLOT(lock()));
            connect(unlock, SIGNAL(clicked()), this, SLOT(unlock()));
            connect(quit, SIGNAL(clicked()),
                    QApplication::instance(), SLOT(quit()));

            QHBoxLayout *l = new QHBoxLayout;
            l->addWidget(lock);
            l->addWidget(unlock);
            l->addWidget(quit);
            setLayout(l);
        }

    public slots:
        void lock() {
          locked = true;
          move(x(), 0); // move window to the top of the screen
        }
        void unlock() { locked = false; }

Do the mouse handling:

    protected:
        void mousePressEvent(QMouseEvent *evt)
        {
            oldPos = evt->globalPos();
        }

        void mouseMoveEvent(QMouseEvent *evt)
        {
            const QPoint delta = evt->globalPos() - oldPos;
            if (locked)
                // if locked, ignore delta on y axis, stay at the top
                move(x()+delta.x(), y()); 
            else
                move(x()+delta.x(), y()+delta.y());
            oldPos = evt->globalPos();
        }

    private:
        bool locked;
        QPoint oldPos;
};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM