第4课_Qt的应用程序类型

控制台应用程序

通过命令行运行的不需要提供任何人机交互图形界面通常被称作系统服务。Qt不仅仅是用户界面工具,它也提供了许多其他的功能。
创建步骤:文件–>新建文件或项目–>Application–>Qt Console Application
注意:创建的路径中不能有中文出现,会报错。

字符串处理功能

#include <QtCore>

// text stream is text-codec aware
QTextStream cout(stdout, QIODevice::WriteOnly);

int main(int argc, char** argv){
    Q_UNUSED(argc)
    Q_UNUSED(argv)

    QString s1("Paris");
    QString s2("London");

    QString s = s1 + " " + s2 + "!";
    cout << s << endl;
}

容器类

#include <QtCore>

QTextStream cout(stdout, QIODevice::WriteOnly);

int main(int argc, char** argv){
    Q_UNUSED(argc);
    Q_UNUSED(argv);

    QString s1("Hello");
    QString s2("Qt");
    QList<QString> list;
    list << s1 << s2;
    QListIterator<QString> iter(list);
    //==QString s = list.join(" ") + "!";
    while(iter.hasNext()) {
        cout << iter.next();
        if(iter.hasNext()) {
            cout << " ";
        }
    }
    cout << "!" << endl;
}

文件IO

#include <QtCore>

int main(int argc, char** argv){
    Q_UNUSED(argc);
    Q_UNUSED(argv);

    QList<QStringList> data;

    QFile file("E:\\Qt_Project\\untitled2\\sample.csv");
    if(file.open(QIODevice::ReadOnly)) {
        QTextStream stream(&file);
            forever {//==(;;)
            QString line = stream.readLine();//Reads one line of text from the stream, and returns it as a QString.
            if(line.isEmpty() || line.isNull()) {
                break;
            }
            QStringList row;
            foreach(const QString& cell, line.split(",")) {
                row.append(cell.trimmed());
            }
            data.append(row);
        }
    }
    QListIterator<QStringList> iter(data);
    while(iter.hasNext()) {
        qDebug() << iter.next();
    }
}

窗口应用程序

基于控制台的应用程序非常方便,但有时候需要一些用户界面。但是基于用户界面的应用程序需要后端来写入/读取文件,使用网络进行通讯或者将数据保存在容器中。
创建步骤:文件–>新建文件或项目–>Application–>Qt Widgets Application–>基类填写QWidget

自定义窗口部件

/*----------------------main.cpp------------------*/
#include "widget.h"
#include "customwidget.h"
#include <QtWidgets>
#include <QScopedPointer>

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    QScopedPointer<QWidget> widget(new CustomWidget());
    widget->resize(240, 120);
    widget->show();
    return app.exec();
}
/*----------------------customwidget.h------------------*/
#ifndef CUSTOMWIDGET_H
#define CUSTOMWIDGET_H

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

class CustomWidget : public QWidget
{
    Q_OBJECT
public:
    explicit CustomWidget(QWidget *parent = 0);
    void paintEvent(QPaintEvent *event);
    void mousePressEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
private:
    QPoint m_lastPos;
};

#endif // CUSTOMWIDGET_H
/*----------------------customwidget.cpp------------------*/
#include "customwidget.h"

CustomWidget::CustomWidget(QWidget *parent) :
    QWidget(parent)
{
}

void CustomWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QRect r1 = rect().adjusted(10,10,-10,-10);
    painter.setPen(QColor("#33B5E5"));
    painter.drawRect(r1);

    QRect r2(QPoint(0,0),QSize(40,40));
    if(m_lastPos.isNull()) {
        r2.moveCenter(r1.center());
    } else {
        r2.moveCenter(m_lastPos);
    }
    painter.fillRect(r2, QColor("#FFBB33"));
}

void CustomWidget::mousePressEvent(QMouseEvent *event)
{
    m_lastPos = event->pos();
    update();
}

void CustomWidget::mouseMoveEvent(QMouseEvent *event)
{
    m_lastPos = event->pos();
    update();
}

widget.cpp/.h文件不修改。图中的方块随着鼠标的拖拽而移动,效果如图所示:

窗口应用程序

桌面窗口

/*----------------------main.cpp------------------*/
#include "widget.h"
#include "customwidget.h"
#include <QtWidgets>
#include <QScopedPointer>

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    QScopedPointer<QWidget> widget(new CustomWidget());
    widget->resize(240, 120);
    widget->show();
    return app.exec();
}
/*----------------------customwidget.h------------------*/
#ifndef CUSTOMWIDGET_H
#define CUSTOMWIDGET_H

#include <QtWidgets>

class CustomWidget : public QWidget
{
    Q_OBJECT
public:
    explicit CustomWidget(QWidget *parent = 0);
private slots:
    void itemClicked(QListWidgetItem* item);
    void updateItem();
private:
    QListWidget *m_widget;
    QLineEdit *m_edit;
    QPushButton *m_button;
};

#endif // CUSTOMWIDGET_H
/*----------------------customwidget.cpp------------------*/
#include "customwidget.h"

CustomWidget::CustomWidget(QWidget *parent) :
    QWidget(parent)
{
    QVBoxLayout *layout = new QVBoxLayout(this);
    m_widget = new QListWidget(this);
    layout->addWidget(m_widget);

    m_edit = new QLineEdit(this);
    layout->addWidget(m_edit);

    m_button = new QPushButton("Quit", this);
    layout->addWidget(m_button);
    setLayout(layout);

    QStringList cities;
    cities << "Paris" << "London" << "Munich";
    foreach(const QString& city, cities) {
        m_widget->addItem(city);
    }

    connect(m_widget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(itemClicked(QListWidgetItem*)));
    connect(m_edit, SIGNAL(editingFinished()), this, SLOT(updateItem()));
    connect(m_button, SIGNAL(clicked()), qApp, SLOT(quit()));
}

void CustomWidget::itemClicked(QListWidgetItem *item)
{
    Q_ASSERT(item);
    m_edit->setText(item->text());
}

void CustomWidget::updateItem()
{
    QListWidgetItem* item = m_widget->currentItem();
    if(item) {
        item->setText(m_edit->text());
    }
}

窗口应用

绘制图形

/*----------------------customwidgetV2.h------------------*/
#ifndef CUSTOMWIDGETV2_H
#define CUSTOMWIDGETV2_H

#include <QtWidgets>

class   : public QWidget
{
    Q_OBJECT
public:
    explicit CustomWidgetV2(QWidget *parent = 0);
private:
    QGraphicsView *m_view;
    QGraphicsScene *m_scene;

};

#endif // CUSTOMWIDGETV2_H
/*----------------------customwidgetV2.cpp------------------*/
#include "customwidgetv2.h"

CustomWidgetV2::CustomWidgetV2(QWidget *parent) :
    QWidget(parent)
{
    m_view = new QGraphicsView(this);
    m_scene = new QGraphicsScene(this);
    m_view->setScene(m_scene);

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setMargin(0);
    layout->addWidget(m_view);
    setLayout(layout);

    QGraphicsItem* rect1 = m_scene->addRect(0,0, 40, 40, Qt::NoPen, QColor("#FFBB33"));
    rect1->setFlags(QGraphicsItem::ItemIsFocusable|QGraphicsItem::ItemIsMovable);
}
/*----------------------main.cpp------------------*/
#include "widget.h"
#include "customwidgetv2.h"
#include <QtWidgets>
#include <QScopedPointer>

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    QScopedPointer<QWidget> widget(new CustomWidgetV2());
    widget->resize(240, 120);
    widget->show();
    return app.exec();
}

效果同自定义窗口部件绘制效果。

附录

编译时出现的问题

问题1: invalid use of incomplete type…
解决方法:Such an error message in Qt usually means that you have to #include < Q…>
参考http://blog.163.com/zhj_44/blog/static/1135752520132582915241/


问题2:error: variable ‘XXX’ has initializer but incomplete type
解决方法:添加XXX头文件
参考https://bbs.csdn.net/topics/360008616


问题3:Qt4中常用的头文件QtGUI在Qt5中无效
解决方法:把#include \换成#include < QtWidgets >
参考https://blog.csdn.net/sinat_24229853/article/details/49976099

本章需记语法点

  • The QTextStream class provides a convenient interface for reading and writing text.
QTextStream();
QTextStream(QIODevice *device);
QTextStream(FILE *fileHandle, QIODevice::OpenMode openMode = QIODevice::ReadWrite);
QTextStream(QString *string, QIODevice::OpenMode openMode = QIODevice::ReadWrite);
QTextStream(QByteArray *array, QIODevice::OpenMode openMode = QIODevice::ReadWrite);
QTextStream(const QByteArray &array, QIODevice::OpenMode openMode = QIODevice::ReadOnly);
  • The Q_UNUSED(name) function indicates to the compiler that the parameter with the specified name is not used in the body of a function. This can be used to suppress compiler warnings while allowing functions to be defined with meaningful parameter names in their signatures.
  • QString QString::trimmed() const——Returns a string that has whitespace removed from the start and the end.Whitespace means any character for which QChar::isSpace() returns true. This includes the ASCII characters ‘\t’, ‘\n’, ‘\v’, ‘\f’, ‘\r’, and ’ ‘.Example:
  QString str = "  lots\t of\nwhitespace\r\n ";
  str = str.trimmed(); // str == "lots\t of\nwhitespace"
  • The QListWidget class provides an item-based list widget.

QListWidget

  • The QListWidgetItem class provides an item for use with the QListWidget item view class.
  • The QLineEdit widget is a one-line text editor.
  • The QPushButton widget provides a command button.
  • The QVBoxLayout class lines up widgets vertically.
  • The setLayout function is sets the layout manager for this widget to layout.If there already is a layout manager installed on this widget, QWidget won’t let you install another.Example:
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(formWidget);
setLayout(layout);
  • QMetaObject::Connection QObject::connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection)
  • The Q_ASSERT function prints a warning message containing the source code file name and line number if test is false.
  • The QGraphicsView class provides a widget for displaying the contents of a QGraphicsScene.
  • The QGraphicsScene class provides a surface for managing a large number of 2D graphical items.
  • The setScene function sets the current scene to scene. If scene is already being viewed, this function does nothing.
  • QGraphicsRectItem *QGraphicsScene::addRect(const QRectF &rect, const QPen &pen = QPen(), const QBrush &brush = QBrush())——Creates and adds a rectangle item to the scene, and returns the item pointer. The geometry of the rectangle is defined by rect, and its pen and brush are initialized to pen and brush.
  • QGraphicsItem::ItemIsMovable——The item supports interactive movement using the mouse. By clicking on the item and then dragging, the item will move together with the mouse cursor. If the item has children, all children are also moved. If the item is part of a selection, all selected items are also moved. This feature is provided as a convenience through the base implementation of QGraphicsItem’s mouse event handlers.
  • QGraphicsItem::ItemIsFocusable——The item supports keyboard input focus (i.e., it is an input item). Enabling this flag will allow the item to accept focus, which again allows the delivery of key events to QGraphicsItem::keyPressEvent() and QGraphicsItem::keyReleaseEvent().

猜你喜欢

转载自blog.csdn.net/github_35003236/article/details/80840894