Qt 笔记-1

编写Qt时, 只要在文件中包含了 QApplication 这个头文件,就可以使用 qApp来指向 app. 比如在写信号与槽时,需要写一个退出功能,只需要包含这个头文件,然后将信号连接到 qApp的 quit() 即可,比如:

connect(m_button, SIGNAL(clicked()), qApp, SLOT(quit()));

下面给出 Qt5 cadaques上面的一个例子。
这个 customwidget.cpp

#include "customwidget.h"
#include <QVBoxLayout>
#include <QLineEdit>
#include <QApplication>


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());
    }
}

下面是 customwidget.h

#ifndef CUSTOMWIDGET
#define CUSTOMWIDGET


#include <QWidget>
#include <QListWidgetItem>
#include <QPushButton>

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

这是main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QScopedPointer<QWidget> widget (new CustomWidget());

    widget->resize(240, 120);
    widget->show();
    return app.exec();
}

这是 widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

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

这是widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include "customwidget.h"

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

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

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

你可能感兴趣的:(Qt 笔记-1)