SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
Ch9.Drag and Drop
        Browny
      23, May, 2011
Outline


• Enabling Drag and Drop
• Supporting Custom Drag Types
• Clipboard Handling
Drag file onto Window (1/4)
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow();

protected:
    void dragEnterEvent(QDragEnterEvent *event);
    void dropEvent(QDropEvent *event);

private:
    bool readFile(const QString &fileName);
    QTextEdit *textEdit;
};
Drag file onto Window (2/4)
       MainWindow::MainWindow()
       {
           textEdit = new QTextEdit;
           setCentralWidget(textEdit);

           textEdit->setAcceptDrops(false);
           setAcceptDrops(true);

           setWindowTitle(tr("Text Editor"));
       }


QTextEdit
setAcceptDrops(false)
                setAcceptDrops(true)
                      MainWindow
Drag file onto Window (3/4)
 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
 {
     if (event->mimeData()->hasFormat("text/plain"))
         event->acceptProposedAction();
 }


Standard MIME types are defined by the Internet Assigned
Numbers Authority (IANA). They consist of a type and a subtype
separated by a slash.

The official list of MIME types is available at http://www.iana.org/
assignments/media-types/
Drag file onto Window (4/4)

void MainWindow::dropEvent(QDropEvent *event)
{
    QList<QUrl> urls = event->mimeData()->urls();
    if (urls.isEmpty())
        return;

    QString fileName = urls.first().toLocalFile();
    if (fileName.isEmpty())
        return;

    if (readFile(fileName))
        setWindowTitle(tr("%1 - %2").arg(fileName)
                                    .arg(tr("Drag File")));
}
Initiate a Drag and Accept a Drop
               (1/4)

• Create a QListWidget subclass that
  supports drag and drop
Initiate a Drag and Accept a Drop
               (2/4)
   class ProjectListWidget : public QListWidget
   {
       Q_OBJECT

   public:
       ProjectListWidget(QWidget *parent = 0);

   protected:
       void mousePressEvent(QMouseEvent *event);
       void mouseMoveEvent(QMouseEvent *event);
       void dragEnterEvent(QDragEnterEvent *event);
       void dragMoveEvent(QDragMoveEvent *event);
       void dropEvent(QDropEvent *event);

   private:
       void performDrag();                        QWidget
                                       5
        QPoint startPos;
   };
Initiate a Drag and Accept a Drop
               (3/4)
ProjectListWidget::ProjectListWidget(QWidget *parent)
    : QListWidget(parent)
{
    setAcceptDrops(true);
}

void ProjectListWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
        startPos = event->pos();
    QListWidget::mousePressEvent(event);
}

void ProjectListWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        int distance = (event->pos() - startPos).manhattanLength();
        if (distance >= QApplication::startDragDistance())
            performDrag();
    }
    QListWidget::mouseMoveEvent(event);
}
Initiate a Drag and Accept a Drop
                   (4/4)
void ProjectListWidget::performDrag()
{
    QListWidgetItem *item = currentItem();
    if (item) {
        QMimeData *mimeData = new QMimeData;
        mimeData->setText(item->text());

         QDrag *drag = new QDrag(this);
         drag->setMimeData(mimeData);                QDrag
         drag->setPixmap(QPixmap(":/images/person.png"));
         if (drag->exec(Qt::MoveAction) == Qt::MoveAction)
             delete item;
     }                       QDrag::exec()
}
void ProjectListWidget::dragEnterEvent(QDragEnterEvent *event)
{
                                          ProjectListWidget
    ProjectListWidget *source =
            qobject_cast<ProjectListWidget *>(event->source());
    if (source && source != this) {
        event->setDropAction(Qt::MoveAction);
        event->accept();
    }
}

void ProjectListWidget::dropEvent(QDropEvent *event)
{
    ProjectListWidget *source =
            qobject_cast<ProjectListWidget *>(event->source());
    if (source && source != this) {
        addItem(event->mimeData()->text());
        event->setDropAction(Qt::MoveAction);
        event->accept();
    }
}
Drag custom data (1/2)
1. Provide arbitrary data as a QByteArray using
   QMimeData::setData() and extract it later
   using QMimeData::data()
2. Subclass QMimeData and re-implement
   formats() and retrieveData() to handle our
   custom data types
3. For drag and drop operations within a
   single application, we can subclass
   QMimeData and store the data using any
   data structure we want
Drag custom data (2/2)

• Drawbacks of Method 1
 ‣ Need	
  to	
  convert	
  our	
  data	
  structure	
  to	
  a	
  
      QByteArray	
  even	
  if	
  the	
  drag	
  is	
  not	
  ul1mately	
  
      accepted
 ‣ Providing	
  several	
  MIME	
  types	
  to	
  interact	
  nicely	
  
      with	
  a	
  wide	
  range	
  of	
  applica=ons,	
  we	
  need	
  to	
  
      store	
  the	
  data	
  several	
  1mes
 ‣ If	
  the	
  data	
  is	
  large,	
  this	
  can	
  slow	
  down	
  the	
  
      applica1on	
  needlessly
Add drag and drop capabilities to a
          QTableWidget (1/3)

   • Method 1
void MyTableWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        int distance = (event->pos() - startPos).manhattanLength();
        if (distance >= QApplication::startDragDistance())
            performDrag();
    }
    QTableWidget::mouseMoveEvent(event);
}
Add drag and drop capabilities to a
              QTableWidget (2/3)
void MyTableWidget::performDrag()
{
    QString plainText = selectionAsPlainText();   Chap4 (p.87)
    if (plainText.isEmpty())
        return;

    QMimeData *mimeData = new QMimeData;
    mimeData->setText(plainText);
    mimeData->setHtml(toHtml(plainText));
    mimeData->setData("text/csv", toCsv(plainText).toUtf8());

    QDrag *drag = new QDrag(this);
    drag->setMimeData(mimeData);
    if (drag->exec(Qt::CopyAction | Qt::MoveAction) == Qt::MoveAction)
        deleteSelection();
}
Add drag and drop capabilities to a
          QTableWidget (3/3)
void MyTableWidget::dropEvent(QDropEvent *event)
{
    if (event->mimeData()->hasFormat("text/csv")) {
        QByteArray csvData = event->mimeData()->data("text/csv");
        QString csvText = QString::fromUtf8(csvData);
        ...
        event->acceptProposedAction();
    } else if (event->mimeData()->hasFormat("text/plain")) {
        QString plainText = event->mimeData()->text();
        ...
        event->acceptProposedAction();
    }
}
           QTableWidget         Html       OK
Subclass QMimeData (1/3)
class TableMimeData : public QMimeData
{
    Q_OBJECT

public:
    TableMimeData(const QTableWidget *tableWidget,
                  const QTableWidgetSelectionRange &range);

     const QTableWidget *tableWidget() const { return myTableWidget; }
     QTableWidgetSelectionRange range() const { return myRange; }
     QStringList formats() const;

protected:
    QVariant retrieveData(const QString &format,
                          QVariant::Type preferredType) const;

private:
    static QString toHtml(const QString &plainText);
    static QString toCsv(const QString &plainText);

     QString text(int row, int column) const;
     QString rangeAsPlainText() const;

     const QTableWidget *myTableWidget;                          ,
     QTableWidgetSelectionRange myRange;
     QStringList myFormats;                 QTableWidget                 ,
};
Subclass QMimeData (2/3)
TableMimeData::TableMimeData(const QTableWidget *tableWidget,
                             const QTableWidgetSelectionRange &range) {
    myTableWidget = tableWidget;
    myRange = range;
    myFormats << "text/csv" << "text/html" << "text/plain";
}

QStringList TableMimeData::formats() const {
    return myFormats;
}

QVariant TableMimeData::retrieveData(const QString &format,
                                      QVariant::Type preferredType) const {
    if (format == "text/plain")
         return rangeAsPlainText();
    else if (format == "text/csv")
         return toCsv(rangeAsPlainText());
    else if (format == "text/html") {
         return toHtml(rangeAsPlainText());
    else
         return QMimeData::retrieveData(format, preferredType);
}
Subclass QMimeData (3/3)
void MyTableWidget::dropEvent(QDropEvent *event)
{
    const TableMimeData *tableData =
            qobject_cast<const TableMimeData *>(event->mimeData());

    if (tableData) {
        const QTableWidget *otherTable = tableData->tableWidget();
        QTableWidgetSelectionRange otherRange = tableData->range();
        ...
        event->acceptProposedAction();
    } else if (event->mimeData()->hasFormat("text/csv")) {
        QByteArray csvData = event->mimeData()->data("text/csv");
        QString csvText = QString::fromUtf8(csvData);
        ...

                                           we can directly access the table
    }
    QTableWidget::mouseMoveEvent(event);   data instead of going through
                                           QMimeData's API
}
Clipboard Handling

• Access clipboard: QApplication::clipboard()
• Built-in functionality might not be sufficient
   (not just text or an image)
  ‣ Subclass	
  QMimeData	
  and	
  re-­‐implement	
  a	
  few	
  virtual	
  
       func=ons	
  
  ‣ Reuse	
  the	
  QMimeData	
  subclass	
  and	
  put	
  it	
  on	
  the	
  
       clipboard	
  using	
  the	
  setMimeData()	
  func=on.	
  To	
  retrieve	
  
       the	
  data,	
  we	
  can	
  call	
  mimeData()	
  on	
  the	
  clipboard

• Clipboard's contents change
  ‣ QClipboard::dataChanged()	
  signal
Thank you :)

Más contenido relacionado

La actualidad más candente

The Ring programming language version 1.10 book - Part 106 of 212
The Ring programming language version 1.10 book - Part 106 of 212The Ring programming language version 1.10 book - Part 106 of 212
The Ring programming language version 1.10 book - Part 106 of 212Mahmoud Samir Fayed
 
Sustaining Test-Driven Development
Sustaining Test-Driven DevelopmentSustaining Test-Driven Development
Sustaining Test-Driven DevelopmentAgileOnTheBeach
 
The Ring programming language version 1.5.3 book - Part 8 of 184
The Ring programming language version 1.5.3 book - Part 8 of 184The Ring programming language version 1.5.3 book - Part 8 of 184
The Ring programming language version 1.5.3 book - Part 8 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.5 book - Part 12 of 31
The Ring programming language version 1.5 book - Part 12 of 31The Ring programming language version 1.5 book - Part 12 of 31
The Ring programming language version 1.5 book - Part 12 of 31Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 8 of 185
The Ring programming language version 1.5.4 book - Part 8 of 185The Ring programming language version 1.5.4 book - Part 8 of 185
The Ring programming language version 1.5.4 book - Part 8 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 7 of 180
The Ring programming language version 1.5.1 book - Part 7 of 180The Ring programming language version 1.5.1 book - Part 7 of 180
The Ring programming language version 1.5.1 book - Part 7 of 180Mahmoud Samir Fayed
 
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...CodiLime
 
The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180Mahmoud Samir Fayed
 
AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleChristopher Curtin
 
Vaadin 7 Today and Tomorrow
Vaadin 7 Today and TomorrowVaadin 7 Today and Tomorrow
Vaadin 7 Today and TomorrowJoonas Lehtinen
 
The Ring programming language version 1.7 book - Part 101 of 196
The Ring programming language version 1.7 book - Part 101 of 196The Ring programming language version 1.7 book - Part 101 of 196
The Ring programming language version 1.7 book - Part 101 of 196Mahmoud Samir Fayed
 
KDD 2016 Streaming Analytics Tutorial
KDD 2016 Streaming Analytics TutorialKDD 2016 Streaming Analytics Tutorial
KDD 2016 Streaming Analytics TutorialNeera Agarwal
 
OpenMAMA Under the Hood
OpenMAMA Under the HoodOpenMAMA Under the Hood
OpenMAMA Under the HoodOpenMAMA
 
Vaadin today and tomorrow
Vaadin today and tomorrowVaadin today and tomorrow
Vaadin today and tomorrowJoonas Lehtinen
 
The Ring programming language version 1.9 book - Part 74 of 210
The Ring programming language version 1.9 book - Part 74 of 210The Ring programming language version 1.9 book - Part 74 of 210
The Ring programming language version 1.9 book - Part 74 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 71 of 202
The Ring programming language version 1.8 book - Part 71 of 202The Ring programming language version 1.8 book - Part 71 of 202
The Ring programming language version 1.8 book - Part 71 of 202Mahmoud Samir Fayed
 
Qtp+real time+test+script
Qtp+real time+test+scriptQtp+real time+test+script
Qtp+real time+test+scriptRamu Palanki
 

La actualidad más candente (20)

Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
 
The Ring programming language version 1.10 book - Part 106 of 212
The Ring programming language version 1.10 book - Part 106 of 212The Ring programming language version 1.10 book - Part 106 of 212
The Ring programming language version 1.10 book - Part 106 of 212
 
Sustaining Test-Driven Development
Sustaining Test-Driven DevelopmentSustaining Test-Driven Development
Sustaining Test-Driven Development
 
The Ring programming language version 1.5.3 book - Part 8 of 184
The Ring programming language version 1.5.3 book - Part 8 of 184The Ring programming language version 1.5.3 book - Part 8 of 184
The Ring programming language version 1.5.3 book - Part 8 of 184
 
The Ring programming language version 1.5 book - Part 12 of 31
The Ring programming language version 1.5 book - Part 12 of 31The Ring programming language version 1.5 book - Part 12 of 31
The Ring programming language version 1.5 book - Part 12 of 31
 
The Ring programming language version 1.5.4 book - Part 8 of 185
The Ring programming language version 1.5.4 book - Part 8 of 185The Ring programming language version 1.5.4 book - Part 8 of 185
The Ring programming language version 1.5.4 book - Part 8 of 185
 
The Ring programming language version 1.5.1 book - Part 7 of 180
The Ring programming language version 1.5.1 book - Part 7 of 180The Ring programming language version 1.5.1 book - Part 7 of 180
The Ring programming language version 1.5.1 book - Part 7 of 180
 
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
 
The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
 
Rxjs vienna
Rxjs viennaRxjs vienna
Rxjs vienna
 
AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading example
 
Vaadin 7 Today and Tomorrow
Vaadin 7 Today and TomorrowVaadin 7 Today and Tomorrow
Vaadin 7 Today and Tomorrow
 
The Ring programming language version 1.7 book - Part 101 of 196
The Ring programming language version 1.7 book - Part 101 of 196The Ring programming language version 1.7 book - Part 101 of 196
The Ring programming language version 1.7 book - Part 101 of 196
 
KDD 2016 Streaming Analytics Tutorial
KDD 2016 Streaming Analytics TutorialKDD 2016 Streaming Analytics Tutorial
KDD 2016 Streaming Analytics Tutorial
 
OpenMAMA Under the Hood
OpenMAMA Under the HoodOpenMAMA Under the Hood
OpenMAMA Under the Hood
 
Vaadin today and tomorrow
Vaadin today and tomorrowVaadin today and tomorrow
Vaadin today and tomorrow
 
The Ring programming language version 1.9 book - Part 74 of 210
The Ring programming language version 1.9 book - Part 74 of 210The Ring programming language version 1.9 book - Part 74 of 210
The Ring programming language version 1.9 book - Part 74 of 210
 
The Ring programming language version 1.8 book - Part 71 of 202
The Ring programming language version 1.8 book - Part 71 of 202The Ring programming language version 1.8 book - Part 71 of 202
The Ring programming language version 1.8 book - Part 71 of 202
 
Qtp+real time+test+script
Qtp+real time+test+scriptQtp+real time+test+script
Qtp+real time+test+script
 

Similar a [C++ gui programming with qt4] chap9

Qt & Webkit
Qt & WebkitQt & Webkit
Qt & WebkitQT-day
 
The Ring programming language version 1.5.3 book - Part 80 of 184
The Ring programming language version 1.5.3 book - Part 80 of 184The Ring programming language version 1.5.3 book - Part 80 of 184
The Ring programming language version 1.5.3 book - Part 80 of 184Mahmoud Samir Fayed
 
Architecting JavaScript Code
Architecting JavaScript CodeArchitecting JavaScript Code
Architecting JavaScript CodeSuresh Balla
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...DroidConTLV
 
The Ring programming language version 1.6 book - Part 86 of 189
The Ring programming language version 1.6 book - Part 86 of 189The Ring programming language version 1.6 book - Part 86 of 189
The Ring programming language version 1.6 book - Part 86 of 189Mahmoud Samir Fayed
 
A Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkA Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkZachary Blair
 
如何透過 Go-kit 快速搭建微服務架構應用程式實戰
如何透過 Go-kit 快速搭建微服務架構應用程式實戰如何透過 Go-kit 快速搭建微服務架構應用程式實戰
如何透過 Go-kit 快速搭建微服務架構應用程式實戰KAI CHU CHUNG
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym Khondar
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš Kypta
 
bai giai de LTWINForm.docx
bai giai de LTWINForm.docxbai giai de LTWINForm.docx
bai giai de LTWINForm.docxVnThanh292761
 
I wanted to change the cloudsrectangles into an actuall image it do.pdf
I wanted to change the cloudsrectangles into an actuall image it do.pdfI wanted to change the cloudsrectangles into an actuall image it do.pdf
I wanted to change the cloudsrectangles into an actuall image it do.pdffeelinggifts
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeMacoscope
 

Similar a [C++ gui programming with qt4] chap9 (20)

Qt & Webkit
Qt & WebkitQt & Webkit
Qt & Webkit
 
Qt Animation
Qt AnimationQt Animation
Qt Animation
 
Gwt RPC
Gwt RPCGwt RPC
Gwt RPC
 
The Ring programming language version 1.5.3 book - Part 80 of 184
The Ring programming language version 1.5.3 book - Part 80 of 184The Ring programming language version 1.5.3 book - Part 80 of 184
The Ring programming language version 1.5.3 book - Part 80 of 184
 
Treinamento Qt básico - aula II
Treinamento Qt básico - aula IITreinamento Qt básico - aula II
Treinamento Qt básico - aula II
 
Architecting JavaScript Code
Architecting JavaScript CodeArchitecting JavaScript Code
Architecting JavaScript Code
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
The Ring programming language version 1.6 book - Part 86 of 189
The Ring programming language version 1.6 book - Part 86 of 189The Ring programming language version 1.6 book - Part 86 of 189
The Ring programming language version 1.6 book - Part 86 of 189
 
A Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkA Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application Framework
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
如何透過 Go-kit 快速搭建微服務架構應用程式實戰
如何透過 Go-kit 快速搭建微服務架構應用程式實戰如何透過 Go-kit 快速搭建微服務架構應用程式實戰
如何透過 Go-kit 快速搭建微服務架構應用程式實戰
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
Qt Widgets In Depth
Qt Widgets In DepthQt Widgets In Depth
Qt Widgets In Depth
 
Qt Widget In-Depth
Qt Widget In-DepthQt Widget In-Depth
Qt Widget In-Depth
 
Jersey Guice AOP
Jersey Guice AOPJersey Guice AOP
Jersey Guice AOP
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
bai giai de LTWINForm.docx
bai giai de LTWINForm.docxbai giai de LTWINForm.docx
bai giai de LTWINForm.docx
 
I wanted to change the cloudsrectangles into an actuall image it do.pdf
I wanted to change the cloudsrectangles into an actuall image it do.pdfI wanted to change the cloudsrectangles into an actuall image it do.pdf
I wanted to change the cloudsrectangles into an actuall image it do.pdf
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 

Más de Shih-Hsiang Lin

Introduction to Apache Ant
Introduction to Apache AntIntroduction to Apache Ant
Introduction to Apache AntShih-Hsiang Lin
 
Introduction to GNU Make Programming Language
Introduction to GNU Make Programming LanguageIntroduction to GNU Make Programming Language
Introduction to GNU Make Programming LanguageShih-Hsiang Lin
 
Ch6 file, saving states, and preferences
Ch6 file, saving states, and preferencesCh6 file, saving states, and preferences
Ch6 file, saving states, and preferencesShih-Hsiang Lin
 
Ch5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internetCh5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internetShih-Hsiang Lin
 
Ch4 creating user interfaces
Ch4 creating user interfacesCh4 creating user interfaces
Ch4 creating user interfacesShih-Hsiang Lin
 
Ch3 creating application and activities
Ch3 creating application and activitiesCh3 creating application and activities
Ch3 creating application and activitiesShih-Hsiang Lin
 
[C++ GUI Programming with Qt4] chap7
[C++ GUI Programming with Qt4] chap7[C++ GUI Programming with Qt4] chap7
[C++ GUI Programming with Qt4] chap7Shih-Hsiang Lin
 
[C++ GUI Programming with Qt4] chap4
[C++ GUI Programming with Qt4] chap4[C++ GUI Programming with Qt4] chap4
[C++ GUI Programming with Qt4] chap4Shih-Hsiang Lin
 
Introduction to homography
Introduction to homographyIntroduction to homography
Introduction to homographyShih-Hsiang Lin
 
Project Hosting by Google
Project Hosting by GoogleProject Hosting by Google
Project Hosting by GoogleShih-Hsiang Lin
 
An Introduction to Hidden Markov Model
An Introduction to Hidden Markov ModelAn Introduction to Hidden Markov Model
An Introduction to Hidden Markov ModelShih-Hsiang Lin
 

Más de Shih-Hsiang Lin (13)

Introduction to Apache Ant
Introduction to Apache AntIntroduction to Apache Ant
Introduction to Apache Ant
 
Introduction to GNU Make Programming Language
Introduction to GNU Make Programming LanguageIntroduction to GNU Make Programming Language
Introduction to GNU Make Programming Language
 
Ch6 file, saving states, and preferences
Ch6 file, saving states, and preferencesCh6 file, saving states, and preferences
Ch6 file, saving states, and preferences
 
Ch5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internetCh5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internet
 
Ch4 creating user interfaces
Ch4 creating user interfacesCh4 creating user interfaces
Ch4 creating user interfaces
 
Ch3 creating application and activities
Ch3 creating application and activitiesCh3 creating application and activities
Ch3 creating application and activities
 
[C++ GUI Programming with Qt4] chap7
[C++ GUI Programming with Qt4] chap7[C++ GUI Programming with Qt4] chap7
[C++ GUI Programming with Qt4] chap7
 
[C++ GUI Programming with Qt4] chap4
[C++ GUI Programming with Qt4] chap4[C++ GUI Programming with Qt4] chap4
[C++ GUI Programming with Qt4] chap4
 
Function pointer
Function pointerFunction pointer
Function pointer
 
Introduction to homography
Introduction to homographyIntroduction to homography
Introduction to homography
 
Git basic
Git basicGit basic
Git basic
 
Project Hosting by Google
Project Hosting by GoogleProject Hosting by Google
Project Hosting by Google
 
An Introduction to Hidden Markov Model
An Introduction to Hidden Markov ModelAn Introduction to Hidden Markov Model
An Introduction to Hidden Markov Model
 

Último

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesShubhangi Sonawane
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 

Último (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 

[C++ gui programming with qt4] chap9

  • 1. Ch9.Drag and Drop Browny 23, May, 2011
  • 2. Outline • Enabling Drag and Drop • Supporting Custom Drag Types • Clipboard Handling
  • 3. Drag file onto Window (1/4) class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(); protected: void dragEnterEvent(QDragEnterEvent *event); void dropEvent(QDropEvent *event); private: bool readFile(const QString &fileName); QTextEdit *textEdit; };
  • 4. Drag file onto Window (2/4) MainWindow::MainWindow() { textEdit = new QTextEdit; setCentralWidget(textEdit); textEdit->setAcceptDrops(false); setAcceptDrops(true); setWindowTitle(tr("Text Editor")); } QTextEdit setAcceptDrops(false) setAcceptDrops(true) MainWindow
  • 5. Drag file onto Window (3/4) void MainWindow::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("text/plain")) event->acceptProposedAction(); } Standard MIME types are defined by the Internet Assigned Numbers Authority (IANA). They consist of a type and a subtype separated by a slash. The official list of MIME types is available at http://www.iana.org/ assignments/media-types/
  • 6. Drag file onto Window (4/4) void MainWindow::dropEvent(QDropEvent *event) { QList<QUrl> urls = event->mimeData()->urls(); if (urls.isEmpty()) return; QString fileName = urls.first().toLocalFile(); if (fileName.isEmpty()) return; if (readFile(fileName)) setWindowTitle(tr("%1 - %2").arg(fileName) .arg(tr("Drag File"))); }
  • 7. Initiate a Drag and Accept a Drop (1/4) • Create a QListWidget subclass that supports drag and drop
  • 8. Initiate a Drag and Accept a Drop (2/4) class ProjectListWidget : public QListWidget { Q_OBJECT public: ProjectListWidget(QWidget *parent = 0); protected: void mousePressEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void dragEnterEvent(QDragEnterEvent *event); void dragMoveEvent(QDragMoveEvent *event); void dropEvent(QDropEvent *event); private: void performDrag(); QWidget 5 QPoint startPos; };
  • 9. Initiate a Drag and Accept a Drop (3/4) ProjectListWidget::ProjectListWidget(QWidget *parent) : QListWidget(parent) { setAcceptDrops(true); } void ProjectListWidget::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) startPos = event->pos(); QListWidget::mousePressEvent(event); } void ProjectListWidget::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { int distance = (event->pos() - startPos).manhattanLength(); if (distance >= QApplication::startDragDistance()) performDrag(); } QListWidget::mouseMoveEvent(event); }
  • 10. Initiate a Drag and Accept a Drop (4/4) void ProjectListWidget::performDrag() { QListWidgetItem *item = currentItem(); if (item) { QMimeData *mimeData = new QMimeData; mimeData->setText(item->text()); QDrag *drag = new QDrag(this); drag->setMimeData(mimeData); QDrag drag->setPixmap(QPixmap(":/images/person.png")); if (drag->exec(Qt::MoveAction) == Qt::MoveAction) delete item; } QDrag::exec() }
  • 11. void ProjectListWidget::dragEnterEvent(QDragEnterEvent *event) { ProjectListWidget ProjectListWidget *source = qobject_cast<ProjectListWidget *>(event->source()); if (source && source != this) { event->setDropAction(Qt::MoveAction); event->accept(); } } void ProjectListWidget::dropEvent(QDropEvent *event) { ProjectListWidget *source = qobject_cast<ProjectListWidget *>(event->source()); if (source && source != this) { addItem(event->mimeData()->text()); event->setDropAction(Qt::MoveAction); event->accept(); } }
  • 12. Drag custom data (1/2) 1. Provide arbitrary data as a QByteArray using QMimeData::setData() and extract it later using QMimeData::data() 2. Subclass QMimeData and re-implement formats() and retrieveData() to handle our custom data types 3. For drag and drop operations within a single application, we can subclass QMimeData and store the data using any data structure we want
  • 13. Drag custom data (2/2) • Drawbacks of Method 1 ‣ Need  to  convert  our  data  structure  to  a   QByteArray  even  if  the  drag  is  not  ul1mately   accepted ‣ Providing  several  MIME  types  to  interact  nicely   with  a  wide  range  of  applica=ons,  we  need  to   store  the  data  several  1mes ‣ If  the  data  is  large,  this  can  slow  down  the   applica1on  needlessly
  • 14. Add drag and drop capabilities to a QTableWidget (1/3) • Method 1 void MyTableWidget::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { int distance = (event->pos() - startPos).manhattanLength(); if (distance >= QApplication::startDragDistance()) performDrag(); } QTableWidget::mouseMoveEvent(event); }
  • 15. Add drag and drop capabilities to a QTableWidget (2/3) void MyTableWidget::performDrag() { QString plainText = selectionAsPlainText(); Chap4 (p.87) if (plainText.isEmpty()) return; QMimeData *mimeData = new QMimeData; mimeData->setText(plainText); mimeData->setHtml(toHtml(plainText)); mimeData->setData("text/csv", toCsv(plainText).toUtf8()); QDrag *drag = new QDrag(this); drag->setMimeData(mimeData); if (drag->exec(Qt::CopyAction | Qt::MoveAction) == Qt::MoveAction) deleteSelection(); }
  • 16. Add drag and drop capabilities to a QTableWidget (3/3) void MyTableWidget::dropEvent(QDropEvent *event) { if (event->mimeData()->hasFormat("text/csv")) { QByteArray csvData = event->mimeData()->data("text/csv"); QString csvText = QString::fromUtf8(csvData); ... event->acceptProposedAction(); } else if (event->mimeData()->hasFormat("text/plain")) { QString plainText = event->mimeData()->text(); ... event->acceptProposedAction(); } } QTableWidget Html OK
  • 17. Subclass QMimeData (1/3) class TableMimeData : public QMimeData { Q_OBJECT public: TableMimeData(const QTableWidget *tableWidget, const QTableWidgetSelectionRange &range); const QTableWidget *tableWidget() const { return myTableWidget; } QTableWidgetSelectionRange range() const { return myRange; } QStringList formats() const; protected: QVariant retrieveData(const QString &format, QVariant::Type preferredType) const; private: static QString toHtml(const QString &plainText); static QString toCsv(const QString &plainText); QString text(int row, int column) const; QString rangeAsPlainText() const; const QTableWidget *myTableWidget; , QTableWidgetSelectionRange myRange; QStringList myFormats; QTableWidget , };
  • 18. Subclass QMimeData (2/3) TableMimeData::TableMimeData(const QTableWidget *tableWidget, const QTableWidgetSelectionRange &range) { myTableWidget = tableWidget; myRange = range; myFormats << "text/csv" << "text/html" << "text/plain"; } QStringList TableMimeData::formats() const { return myFormats; } QVariant TableMimeData::retrieveData(const QString &format, QVariant::Type preferredType) const { if (format == "text/plain") return rangeAsPlainText(); else if (format == "text/csv") return toCsv(rangeAsPlainText()); else if (format == "text/html") { return toHtml(rangeAsPlainText()); else return QMimeData::retrieveData(format, preferredType); }
  • 19. Subclass QMimeData (3/3) void MyTableWidget::dropEvent(QDropEvent *event) { const TableMimeData *tableData = qobject_cast<const TableMimeData *>(event->mimeData()); if (tableData) { const QTableWidget *otherTable = tableData->tableWidget(); QTableWidgetSelectionRange otherRange = tableData->range(); ... event->acceptProposedAction(); } else if (event->mimeData()->hasFormat("text/csv")) { QByteArray csvData = event->mimeData()->data("text/csv"); QString csvText = QString::fromUtf8(csvData); ... we can directly access the table } QTableWidget::mouseMoveEvent(event); data instead of going through QMimeData's API }
  • 20. Clipboard Handling • Access clipboard: QApplication::clipboard() • Built-in functionality might not be sufficient (not just text or an image) ‣ Subclass  QMimeData  and  re-­‐implement  a  few  virtual   func=ons   ‣ Reuse  the  QMimeData  subclass  and  put  it  on  the   clipboard  using  the  setMimeData()  func=on.  To  retrieve   the  data,  we  can  call  mimeData()  on  the  clipboard • Clipboard's contents change ‣ QClipboard::dataChanged()  signal