#include "mainwindow.h" #include <QApplication> #include <QTextEdit> int main(int argc, char **argv) { QApplication a(argc, argv); QTextEdit textEdit; textEdit.show(); return a.exec(); }
运行结果如下:
#include "mainwindow.h" #include <QApplication> #include <QTextEdit> #include <QVBoxLayout> #include <QPushButton> #include <QWidget> int main(int argc, char **argv) { QApplication a(argc, argv); QTextEdit *textEdit = new QTextEdit; QPushButton *quitButton = new QPushButton("&Quit"); QObject::connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(textEdit); layout->addWidget(quitButton); QWidget *window = new QWidget; window->setLayout(layout); window->show(); return a.exec(); }
上段代码中,我们定义了quitButton对象,并通过信号槽机制将按钮点击事件与程序退出联系起来。这里也是用了垂直框布局QVBoxLayout,addWidget()方法将部件添加入布局中,其参数应是一个部件的指针,一个布局可以添加多个部件。最后,对象window将其布局设置为layout。可以看到QPunshButton的label中Quit前面有&字符,说明快捷键ALT+Q将激活该按钮的按下动作;要转义&,直接&&即可。代码里的qApp值得去解释一下,下面整理自https://qt-project.org/forums/viewthread/14061/:
qApp is a globally accessible pointer to the QApplication object, this is a pointer to the object for which the member function is called. -------- you should use qApp when you want to call function/slot from QCoreApplication. this is used when you call slot that belongs to the class where you are at that moment. -------- You use qApp macro (this one is a pointer to the QApplication object) when you want your application to… in your case ‘quit’ – might be some different functionality specific to the QApplication instance运行结果如下:
QWidget *window = new QWidget; window->setLayout(layout); window->show();改成
MainWindow *window = new MainWindow; window->setLayout(layout); window->show();
后运行出现以下信息:
QWidget::setLayout: Attempting to set QLayout "" on MainWindow "MainWindow", which already has a layout
运行结果是mainwindow.ui定义的布局。暂不去涉猎。
另外notepad.pro文件内容在添加文件时会变化,qmake会用到pro文件。