Widget空窗口
this->setWindowTitle("我的窗口");//設置窗口標題this->resize(500,300);//設置窗口大小this->setFixedSize(500,300);//設置固定大小(無法拖拽)
此時,窗口大小發生改變,且窗口名稱改變,窗口無法再拖動改變大小
常用的基礎部件
Qt提供了很多部件,可以開發出圖形化的用戶界面,使用這些控件時需要先引入頭文件
QLabel
常用方法:
// 創建 QLabel 對象QLabel *l1 = new QLabel;// 設置文本內容l1->setText("Hello,你好啊!!!");// 設置文本顯示位置l1->move(100, 100);// 設置文本區域大小l1->resize(200, 100);// 設置文本對齊方式, 默認水平左對齊 垂直中對齊l1->setAlignment(Qt::AlignHCenter | Qt::AlignTop);// 設置文本使用字體l1->setFont(QFont("楷體"));// 將文本框加入到父級,也就是 Widget 空窗口中l1->setParent(this);
此時運行,在窗口內就可以顯示出效果
QFont
QFont是用來設置字體的,常用方法有:
QLabel *l2 = new QLabel("QFont字體測試", this);//這是Qlabel的構造函數重載,可以直接設置內容,和指定parent,和setParent和setText這兩句代碼效果一致// 設置字體QFont font;//創建對象font.setBold(true);//是否加粗font.setFamily("楷體");//設置字形font.setItalic(true);//是否傾斜font.setPointSize(20);//設置字號font.setWeight(QFont::Black);//設置加粗// 設置l2應用字體l2->setFont(font);
此時運行可以看到效果
QPushButton
是一個按鈕
//方法一:
QPushButton *btn1 = new QPushButton;
btn1->setText("按鈕1");
btn1->resize(80, 30);
btn1->move(50, 0);
btn1->setParent(this);// 參數1: 按鈕中的文本
// 參數2: 父組件設置
QPushButton *btn2 = new QPushButton("按鈕2", this);
btn2->move(200, 0);
btn2->setFont(QFont("楷體"));
QLineEdiit
是一個單行文本框,常用的方法有
QLineEdit *txt = new QLineEdit;
txt->resize(100, 40);//設置大小
txt->setText("請輸入內容");//設置文本內容
txt->resize(100, 30);
txt->move(200, 30);//移動位置
txt->setParent(this);//設置在哪個窗口
可以通過這些控件制作一個登錄界面
// 窗口設置this->setWindowTitle("游戲登錄");//設置標題this->setFixedSize(500, 300);//設置固定大小// 請登錄標題QLabel *loginLabel = new QLabel("請登錄", this);//新建一個label然后指定父和內容loginLabel->setFont(QFont("黑體", 30, QFont::Black));//字體loginLabel->resize(150, 50);//指定大小loginLabel->move(177, 20);//移動位置// 提供給賬號和密碼標簽使用的字體QFont f("黑體", 14);// 賬號設置QLabel *accountLabel = new QLabel("賬號:", this);accountLabel->move(85, 98);accountLabel->setFont(f);QLineEdit *accoutEdit = new QLineEdit(this);accoutEdit->move(140, 95);accoutEdit->resize(250, 40);accoutEdit->setPlaceholderText("賬號名/手機號/郵箱");// 密碼設置QLabel *pwdLabel = new QLabel("密碼:", this);pwdLabel->move(85, 160);pwdLabel->setFont(f);QLineEdit *pwdEdit = new QLineEdit(this);pwdEdit->move(140, 155);pwdEdit->resize(250, 40);pwdEdit->setPlaceholderText("密碼");// setEchoMode 用來設置QLineEdit 中的文本狀態// QLineEdit::Normal: 正常狀態,明文顯示// QLineEdit::Password: 密碼狀態, 密文顯示// QLineEdit::PasswordEchoOnEdit: 輸入時明文,失焦時密文pwdEdit->setEchoMode(QLineEdit::Password);// 切換按鈕QPushButton *chgBtn = new QPushButton("明文", this);chgBtn->resize(60, 40);chgBtn->move(330, 155);// 重置和登錄按鈕QPushButton *resetBtn = new QPushButton("重置", this);QPushButton *loginBtn = new QPushButton("登錄", this);resetBtn->resize(80, 40);loginBtn->resize(80, 40);resetBtn->move(135, 220);loginBtn->move(285, 220);