Qt学习(001-3)

Qt5.1.1建立项目notepad。

这次用子类来实现简单的notepad。

建立头文件notepad.h:

#ifndef NOTEPAD_H
#define NOTEPAD_H

#include <QWidget>
#include <QTextEdit>
#include <QVBoxLayout>
#include <QPushButton>
#include <QMessageBox>

class Notepad : public QWidget
 {
     Q_OBJECT

 public:
     Notepad();

private slots:
     void quit();

 private:
     QTextEdit *textEdit;
     QPushButton *quitButton;
 };

#endif // NOTEPAD_H



Q_OBJECT已经在 Qt(001)解释过。quit()函数是一个信号槽中的槽。notepad会调用自己定义的槽。

建立cpp文件notepad.cpp:

#include <notepad.h>

#include <QApplication>

Notepad::Notepad()
{
    textEdit = new QTextEdit;
    quitButton = new QPushButton(tr("Quit"));
    connect(quitButton, SIGNAL(clicked()), this, SLOT(quit()));
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(textEdit);
    layout->addWidget(quitButton);
    setLayout(layout);
    setWindowTitle(tr("Notepad"));
}
void Notepad::quit()
{
  QMessageBox messageBox;
  messageBox.setWindowTitle(tr("Notepad"));
  messageBox.setText(tr("Do you really want to quit?"));
  messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
  messageBox.setDefaultButton(QMessageBox::No);
  if (messageBox.exec() == QMessageBox::Yes)
      qApp->quit();
}

tr()函数属于类QObject,所有使用了Q_OBJECT宏的类都自动具有tr()的函数,tr用来实现国际化。


修改main.cpp:

#include "notepad.h"

#include <QApplication>

#include <QWidget>


int main(int argc, char **argv)
{
    QApplication a(argc, argv);

    Notepad  *notepad = new Notepad;
    notepad->show();

    return a.exec();
}



运行结果:
Qt学习(001-3)
点击quit按钮时:
Qt学习(001-3)


参考:

http://qt-project.org/doc/qt-4.8/gettingstartedqt.html

你可能感兴趣的:(qt)