图片拖动并交换图片
Posted 邶风
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图片拖动并交换图片相关的知识,希望对你有一定的参考价值。
Hero.h
#ifndef HERO_H #define HERO_H #include <QToolButton> #include <QMouseEvent> class Hero : public QToolButton { Q_OBJECT public: explicit Hero(QWidget *parent = nullptr); ~Hero(); public: void setImage(const QString&); protected: void mousePressEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); private: QPoint m_pressPoint;//鼠标按下的位置 QPoint m_pressPointUI;//鼠标按下时控价的位置 }; #endif // HERO_H
#include "Hero.h" #include "mainwindow.h" #include <QDebug> Hero::Hero(QWidget *parent) : QToolButton(parent) { m_pressPointUI = this->pos(); } Hero::~Hero() { } void Hero::setImage(const QString& s_image) { // QImage image(s_image); // int w = image.width(); // int h = image.height(); int w = 80; int h = 80; this->setFixedSize(w,h); this->setIconSize(QSize(w,h)); this->setIcon(QIcon(s_image)); } void Hero::mousePressEvent(QMouseEvent *event) { m_pressPoint = event->pos(); m_pressPointUI = this->pos(); this->raise(); } void Hero::mouseMoveEvent(QMouseEvent *event) { QPoint dis = event->pos() - m_pressPoint; this->move(this->pos() + dis); } void Hero::mouseReleaseEvent(QMouseEvent *event) { for (int i =0;i<MainWindow::mHero.size();i++) { if (MainWindow::mHero[i]->geometry().contains(this->pos() + event->pos()) && this != MainWindow::mHero[i]) { //交换图片 QIcon icon = this->icon(); this->setIcon(MainWindow::mHero[i]->icon()); MainWindow::mHero[i]->setIcon(icon); } } this->move(m_pressPointUI); }
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include "Hero.h" #include <QMainWindow> #include <QVector> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); void init(); public: static QVector<Hero*> mHero; private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
#include "mainwindow.h" #include "ui_mainwindow.h" QVector<Hero*> MainWindow::mHero; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); init(); } MainWindow::~MainWindow() { // for (auto p : mHero) // { // delete p; // p = nullptr; // } // mHero.clear(); delete ui; } void MainWindow::init() { Hero* p1 = new Hero(this); p1->setImage("D:/ss/s3/untitled/image/h1.jpeg"); p1->move(0,0); Hero* p2 = new Hero(this); p2->setImage("D:/ss/s3/untitled/image/h2.jpeg"); p2->move(410,0); Hero* p3 = new Hero(this); p3->setImage("D:/ss/s3/untitled/image/h3.jpeg"); p3->move(0,410); Hero* p4 = new Hero(this); p4->setImage("D:/ss/s3/untitled/image/h4.jpeg"); p4->move(410,410); mHero.append(p1); mHero.append(p2); mHero.append(p3); mHero.append(p4); }
以上是关于图片拖动并交换图片的主要内容,如果未能解决你的问题,请参考以下文章