QT 自定義類訪問UI控制項

2021-10-06 09:25:58 字數 1794 閱讀 2969

qt 自定義類訪問ui控制項的幾種方法

qt建立窗體工程,一般在mainwindow或dialog類裡可以直接通過ui指標訪問控制項,但是新增新的類後又如何訪問呢,可以通過以下幾種方式:

1.將ui指標公開後直接訪問

(1)例如有個自己定義的類customclass,在自定義類裡包含主介面指標mainwindow *

class mainwindow;

class customclass

;

(2)主介面類將成員ui::mainwindow *ui 從私有private移動到public公共

class mainwindow : public qmainwindow

(3)自定義類包含標頭檔案:#include 「ui_mainwindow.h」,構造的時候傳入介面指標mainwindow*,就能通過 mainwidow->ui指標訪問ui控制項了。

#include "mainwindow.h"

#include "ui_mainwindow.h"

customclass::customclass(mainwindow * parent)

void customclass::setui()

記得要引用ui_mainwindow.h,不然會報錯誤:

error: member access into incomplete type 『ui::mainwindow』

forward declaration of 『ui::mainwindow』

2.封裝成公共函式

(1)所有對ui的操作都在主介面mainwindow類中,並封裝成公共的函式

class mainwindow : public qmainwindow

void mainwindow::setui()

(2)其他類要訪問ui呼叫函式就好了

customclass::customclass(mainwindow * parent)

3.通過控制項指標訪問

如果每次只訪問一兩個控制項的話,也可以直接將控制項指標傳給自定義類

customclass=new customclass(this);

customclass->setui(ui->pushbutton);

void customclass::setui(qpushbutton* btn)

4.通過訊號和槽訪問

前面的方法一般夠用了,但如果是多執行緒就必須用到訊號和槽機制,因為非ui執行緒不能跨執行緒訪問ui,例如定義乙個執行緒類

class mythread :public qthread

;

在主介面mainwindow類裡有訊號setui,和槽函式setui,所有對 ui的操作都封裝在槽函式函式中

mainwindow::mainwindow(qwidget *parent)

: qmainwindow(parent)

, ui(new ui::mainwindow)

void mainwindow::setui()

在非ui執行緒裡需要訪問ui通過傳送訊號就行了,槽函式會在ui執行緒中被執行

void mythread::run()

當然訊號和槽很靈活,不一定在多執行緒中,有需要都可以用。

QT 自定義類訪問UI控制項的幾種方法

qt建立窗體工程,一般在mainwindow或dialog類裡可以直接通過ui指標訪問控制項,但是新增新的類後又如何訪問呢,可以通過以下幾種方式 1 例如有個自己定義的類customclass,在自定義類裡包含主介面指標mainwindow class mainwindow class custom...

QT 自定義UI控制項自適應視窗大小

先上 cbmtool new cbmtool this this不可省略 ui gridlayout 3 addwidget cbmtool cbmtool setgeometry 200,50,704,600 cbmtool show 首先cbmtool是乙個qwidget的型別變數 如果想固定控...

Qt 自定義控制項(電池)

閒著蛋疼就做了乙個簡單的自定義電池控制項。其實想了想還挺多地方可以用的啦。效果圖。通過公有方法可修改電量,設定警戒電量,設定是否正在充電,根據需要設定漸變色,圓角,步長。public bool setvalue double v bool setminvalue double v bool setm...