1. 通过设计师生成ui文件
2. 将ui文件转为c++头文件并使用
- 这里生成ui_CalculatorDialog.h是为了更清楚整个构建过程, 一般make会自动做这一步
- 下面的代码是组合的方式来构建的。(注意要写析构函数销毁ui对象)
ui_CalculatorDialog.h
......
class Ui_CalculatorDialog
{
public:QHBoxLayout *horizontalLayout;QLineEdit *m_editZ;QLabel *m_label;QLineEdit *m_editY;QPushButton *m_button;QLineEdit *m_editX;......void setupUi(QDialog *CalculatorDialog) {......}void retranslateUi(QDialog *CalculatorDialog){......}
};
namespace Ui {class CalculatorDialog: public Ui_CalculatorDialog {};
} QT_END_NAMESPACE#endif
CalculatorDialog.h
#ifndef __CALCULATORDIALOG_H
#define __CALCULATORDIALOG_H
#include "ui_CalculatorDialog.h"
#include class CalculatorDialog:public QDialog{Q_OBJECT
public:CalculatorDialog(void);~CalculatorDialog(void);
public slots:void enableBUtton(void);void calcClicked(void);
private:Ui::CalculatorDialog* ui;
};
#endif
CalculatorDialog.cpp
#include "CalculatorDialog.h"
#include
#include
CalculatorDialog::CalculatorDialog(void):ui(new Ui::CalculatorDialog){ui->setupUi(this);ui->m_editX->setValidator(new QDoubleValidator(this)); QObject::connect(ui->m_editX, SIGNAL(textChanged(const QString &)), this, SLOT(enableBUtton(void)));QObject::connect(ui->m_editY, SIGNAL(textChanged(const QString &)), this, SLOT(enableBUtton(void)));QObject::connect(ui->m_button, SIGNAL(clicked(void)), this, SLOT(calcClicked(void)));
}
CalculatorDialog::~CalculatorDialog(void){delete ui;
}
void CalculatorDialog::enableBUtton(void){bool bXOk, bYOk;ui->m_editX->text().toDouble(&bXOk);ui->m_editY->text().toDouble(&bYOk);ui->m_button->setEnabled(bXOk && bYOk);
}
void CalculatorDialog::calcClicked(void){double res = ui->m_editX->text().toDouble() + ui->m_editY->text().toDouble();QString str = QString::number(res);ui->m_editZ->setText(str);
}
main.cpp
#include "CalculatorDialog.h"
#include int main(int argc, char** argv){QApplication app(argc, argv);CalculatorDialog cal;cal.show();return app.exec();
}
result: