Qt 計算器界面實現


學習目的:

  QWidget  QPushbutton  QLineEdit使用。

  通過Qt 代碼實現一個計算器界面。

 

 

QWidget窗口組件:

  QWidget類繼承自 QObject 類和QPaintDevice

  QObject 是所有 支持Qt對象模型 的基類

  QPaintDevice Qt中所有 可繪制組件 的基類

 

 

   QWidget能夠繪制自己 和處理 用戶的輸入

  QWidget 是Qt所有窗口組件類的父類  

   QWidget 是所有窗口組件的抽象

  Qt中的每個窗口組件都是一個QWidget

  QWidget 類對象常作為 父組件 或 頂級組件 使用

 

QLineEdit組件:

  QLineEdit 用於接受用戶輸入

  QLineEdit 能夠獲取用戶輸入字符串

  QLineEdit 功能性組件,需要父組件作為容器

  QLineEdit 能夠在父組件中進行定位

QPushButton組件:

  QPushButton 用於接受用戶點擊事件

  QPushButton 能夠顯示提示性字符串

  QPushButton 功能性組件,需要父組件作為容器

  QPushButton 能夠在父組件中進行定位

 

 

步驟一:

  使用QWidget 繪制窗口。

  頭文件:  

#include <QtGui/QApplication>
#include <QWidget>

    

    實現代碼:  

QWidget* w = new QWidget(NULL,Qt::WindowCloseButtonHint);//構造一個 QWidget 對象 關閉窗體最大化 最小化
  w->show();//顯示主窗體
 w->setFixedSize(w->width(),w->height());//固定窗體大小 禁止窗體通過鼠標放大縮小

運行效果:

  

 

 

步驟二 增加顯示框

  Qwidget + QLlineEdit 組件實現,計算器顯示框。

包含頭文件

  #include <QLineEdit>

實現代碼:

  

 QWidget* w = new QWidget(NULL,Qt::WindowCloseButtonHint);//構造一個 QWidget 對象 關閉窗體最大化 最小化
    QLineEdit* le = new QLineEdit(w);//QLineEdit 父組件為Qwidget
/*設置 QLineEdit 控件大小位置*/
    le->resize(240,30);//設置 寬 高
    le->move(10,10); // 設置起始坐標
    le->setReadOnly(true);//設置 QLineEdit 屬性為只讀

    w->show();//顯示主窗體
    w->setFixedSize(w->width(),w->height());//固定窗體大小 禁止窗體通過鼠標放大縮小

運行效果:

  

 

 步驟三 添加計算器按鍵:

  Qwidget + QLlineEdit +QPushButton組件實現,計算器界面。

 包含頭文件:

  

#include <QtGui/QApplication>
#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
代碼:
  
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget* w = new QWidget(NULL,Qt::WindowCloseButtonHint);//構造一個 QWidget 對象 關閉窗體最大化 最小化
    QLineEdit* le = new QLineEdit(w);//QLineEdit 父組件為Qwidget
    QPushButton *button[20] = {0};//按鈕數組  20 個按鈕
    const char* buttonsText[20] =
    {
        "7", "8", "9", "+", "(",
        "4", "5", "6", "-", ")",
        "1", "2", "3", "*", "<-",
        "0", ".", "=", "/", "C",
    };
    int ret = 0;


    /*創建20 個按鈕*/
    for(int i = 0; i<4 ;i++)
    {
        for(int j=0 ; j<5 ;j++)
        {
            button[i*5 + j] = new QPushButton(w);//QpushButton 父組件為 QWidget
            button[i*5 + j] ->resize(40,40);//設置buttton 控件大小  40 *40
            button[i*5 + j] ->move(10+(10+40)*j,50+(10+40)*i); //設置button 控件偏移
            button[i*5 + j] ->setText(buttonsText[i*5 + j]);//設置button 控件顯示字符
        }
    }
    /*設置 QLineEdit 控件大小位置*/
    le->resize(240,30);//設置 寬 高
    le->move(10,10); // 設置起始坐標
    le->setReadOnly(true);//設置 QLineEdit 屬性為只讀

    w->show();//顯示主窗體
    w->setFixedSize(w->width(),w->height());//固定窗體大小 禁止窗體通過鼠標放大縮小
    ret = a.exec();
    delete w;
    return ret;
}

運行效果:

  

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM