Qt Application Main Window: Drag and Drop and Print Documentation

1. Drag and drop operation

For a practical application, it is not only hoped that a file can be opened from the file menu, but also that the file on the desktop can be dragged directly to the program interface to open it, just like the .pro file can be dragged into Creator to open Same for the whole project. Qt provides a powerful drag and drop mechanism, you can check the Drag and Drop keyword in the help to understand. Drag and drop operations are divided into drag (Drag) and drop (Drop) two operations. When the data is dragged, it will be stored as MIME (Multipurpose Internet Mail Extensions) type. In Qt, use the QMimeData class to represent the MIME type data, and use the QDrag class to complete the data conversion. And the whole drag and drop operation is done in several mouse events and drag and drop events.

1.1 Open files using drag and drop

Let's look at a very simple example, which is to drag the txt text file on the desktop into the program to open it. Create a new Qt Gui application, change the project name to myDragDrop and keep the base class MainWindow and QMainWindow unchanged. After the project is created, drag a Text Edit component into the interface. Then add the function declaration in the mainwindow.h file:

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

Then add the header file to the mainwindow.cpp file:

#include <QDragEnterEvent>
#include <QUrl>
#include <QFile>
#include <QTextStream>
#include <QMimeData>

Then the constructor of the mainwindow class modifies the bits:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setAcceptDrops(true);
}

Finally, define two event handlers:

void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    if(event->mimeData()->hasUrls())
        event->acceptProposedAction();
    else
        event->ignore();
}

void MainWindow:: dropEvent(QDropEvent *event)
{
    const QMimeData *mimeData = event->mimeData();      // 获取MIME数据
    if(mimeData->hasUrls()){                            // 如果数据中包含URL
        QList<QUrl> urlList = mimeData->urls();         // 获取URL列表
        // 将其中第一个URL表示为本地文件路径
        QString fileName = urlList.at(0).toLocalFile();
        if(!fileName.isEmpty()){                        // 如果文件路径不为空
            QFile file(fileName);     // 建立QFile对象并且以只读方式打开该文件
            if(!file.open(QIODevice::ReadOnly)) return;
            QTextStream in(&file);                      // 建立文本流对象
            ui->textEdit->setText(in.readAll());  // 将文件中所有内容读入编辑器
        }
    }
}

When the mouse drags a piece of data into the main window, it will trigger the dragEvemEvem() event processing function, get the MIME data in it, and then check whether it contains the URL path, because the dragged text file is actually dragging it path, this is the function realized by event→mimeData()→hasUrls(). If there is such data, it is received, otherwise the event is ignored. Several functions are provided in the QMimeData class to conveniently handle common MIME data, as shown in the figure below. When the left mouse button is released and the data is dropped into the main window, the dropEvent() event processing function will be triggered. Here, the URL list in the MIME data is obtained. Because only one file is dragged in, the first one in the list is obtained. entry and convert it to a local file path using the toLocalFile() function. Then use QFile and QTextStream to read the data from the file into the editor. At this time, run the program first, and then drag a text file into the program from the desktop.

1.2 Custom drag and drop operation

There is also an example of dragging a picture in a window in the book, that is, there is a picture in the window, and you can drag it at will. Here you need to use a custom MIME type. (Project source path: src\05\5-8\imageDrag|Drop). Due to space reasons, it will not be described in detail here.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

2. Print documents

Qt provides a convenient function of printing documents. You only need to use a QPrinter class and a print dialog box QPrintDialog class to complete the document printing operation. In this section, we will briefly introduce operations such as printing documents, printing previews, and producing PDF documents. You can also view the Printing with Qt keywords in the help.

Create a new Qt Gui application, change the project name to myPrint, keep the class name and base class MainWindow and QMainWindow unchanged. Then drag a Text Edit to the interface in the design mode, and then declare several slots in the mainwindow.h file:

private slots:
    void doPrint();
    void doPrintPreview();
    void printPreview(QPrinter *printer);
    void createPdf();

Then add the header file to the mainwindow.cpp file:

#include <QPrinter>
#include <QPrintDialog>
#include <QPrintPreviewDialog>
#include <QFileDialog>
#include <QFileInfo>

Define several actions in the constructor:

QAction *action_print = new QAction(tr("打印"),this);
QAction *action_printPreview = new QAction(tr("打印预览"),this);
QAction *action_pdf = new QAction(tr("生成pdf"),this);
connect(action_print,SIGNAL(triggered()),this,SLOT(doPrint()));
   connect(action_printPreview,SIGNAL(triggered()),this,SLOT(doPrintPreview()));
connect(action_pdf,SIGNAL(triggered()),this,SLOT(createPdf()));
    ui->mainToolBar->addAction(action_print);
    ui->mainToolBar->addAction(action_printPreview);
    ui->mainToolBar->addAction(action_pdf);

Then add the definitions of those slots:

void MainWindow::doPrint()                    // 打印
{
    QPrinter printer;                         // 创建打印机对象
    QPrintDialog dlg(&printer, this);         // 创建打印对话框
    // 如果编辑器中有选中区域,则打印选中区域
    if (ui->textEdit->textCursor().hasSelection())
        dlg.addEnabledOption(QAbstractPrintDialog::PrintSelection);
    if (dlg.exec() == QDialog::Accepted) {    // 如果在对话框中按下了打印按钮
        ui->textEdit->print(&printer);        // 则执行打印操作
    }
}

Here, the QPrinter class object is established first, which represents a printing device. Then created a print dialog that prints the area if there is a selected area in the editor, otherwise prints the entire page.

void MainWindow::doPrintPreview()                    // 打印预览
{
    QPrinter printer;
    QPrintPreviewDialog preview(&printer, this);     // 创建打印预览对话框
    // 当要生成预览页面时,发射paintRequested()信号
    connect(&preview, &QPrintPreviewDialog::paintRequested,
            this, &MainWindow::printPreview);
    preview.exec();
}

void MainWindow::printPreview(QPrinter *printer)
{
    ui->textEdit->print(printer);
}

Here we mainly use the print preview dialog box for print preview. Here we need to link its paimRequestedO signal to our slot, call the editor's print function in the slot, and use the passed QPrinter class object pointer as a parameter.

void MainWindow::createPdf()                // 生成PDF文件
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("导出PDF文件"),
                                                    QString(), "*.pdf");
    if (!fileName.isEmpty()) {
        if (QFileInfo(fileName).suffix().isEmpty())
            fileName.append(".pdf");        // 如果文件后缀为空,则默认使用.pdf
        QPrinter printer;
        printer.setOutputFormat(QPrinter::PdfFormat);    // 指定输出格式为pdf
        printer.setOutputFileName(fileName);
        ui->textEdit->print(&printer);
    }
}

In the slot for generating PDF documents, use the file dialog box to obtain the path to save the file, and add the suffix "pdf" if the file name does not specify a suffix. Then specify the output format and file path for the QPrinter object, so that the document can be Printed in PDF format. Now run the program, if no printer is installed, the print dialog box that pops up will not be able to use the print operation, and the print preview dialog box will not see the real effect.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Guess you like

Origin blog.csdn.net/QtCompany/article/details/131667935