QT實現可拖動自定義控制元件

熊來闖一闖發表於2023-04-06

使用QT實現自定義類卡牌控制元件Card,使其能在父類視窗上使用滑鼠進行拖動。

 

 

控制元件類標頭檔案card.h

#ifndef CARD_H
#define CARD_H

#include <QWidget>
#include <QPaintEvent>
#include <QPainter>
#include <QMouseEvent>

class Card:public QWidget
{
    Q_OBJECT
public:
    explicit Card(QWidget *parent = nullptr);
    ~Card();
protected:
    void paintEvent(QPaintEvent *event) override;
    void mousePressEvent(QMouseEvent *event) override;
signals:
    void sendSelf(Card *w);
};

#endif // CARD_H

控制元件類標頭檔案card.cpp

#include "card.h"

Card::Card(QWidget *parent):QWidget(parent)
{
    this->setGeometry(0,0,200,400);       //設定控制元件視窗大小
}

Card::~Card()
{

}

void Card::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);                               //建立畫筆
    painter.setRenderHint(QPainter::Antialiasing,true);
    QBrush brush;                                         //建立筆刷
    brush.setColor(Qt::yellow);                           //設定筆刷顏色
    brush.setStyle(Qt::SolidPattern);                     
    painter.setBrush(brush);                              //設定畫筆筆刷
    painter.drawRoundedRect(QRectF(5,5,190,390),10,10);   //繪製圓角矩形並填充
}

void Card::mousePressEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
    emit sendSelf(this);                                  //訊號傳送該控制元件地址
}

以上是基於widget類的控制元件類;

父視窗標頭檔案mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "card.h"
#include <QDebug>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    Card* cd[8];
    Card *temp;
    QPoint startP;
    QPoint yuanP;

private slots:
    void getObject(Card *w);

protected:
    void mouseMoveEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;
};

#endif // MAINWINDOW_H

父視窗標頭檔案mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    for(int i=0;i<8;i++)
    {
        cd[i] = new Card(this);
        connect(cd[i],&Card::sendSelf,this,&MainWindow::getObject);
        cd[i]->move(i%4*200,i/4*400+20);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

//獲取控制元件座標
void MainWindow::getObject(Card *w)
{
    temp = w;
    startP = cursor().pos()-this->pos();
    yuanP = temp->pos();
    /*將此小部件提升到父小部件堆疊的頂部*/
    temp->raise();
}

//移動事件
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    temp->move(yuanP.x()+event->x()-startP.x(),yuanP.y()+event->y()-startP.y());
}

//拖拽物件置頂,卡牌積壓的時候,拖動的那張卡牌置頂
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    temp->raise();
}

以下是工程原始碼:

連結:https://pan.baidu.com/s/1YH95FzZV7_idanob2qeHig
提取碼:wbsy

 

相關文章