溫馨提示×

qt怎么獲取另外窗口的控件值

qt
小億
284
2023-11-08 23:31:23
欄目: 編程語言

要獲取另外窗口的控件值,你可以使用Qt的信號與槽機制來實現(xiàn)。下面是一個示例代碼,演示了如何獲取另一個窗口中一個標簽的文本值:

// 另一個窗口的類
class AnotherWindow : public QWidget
{
    Q_OBJECT

public:
    explicit AnotherWindow(QWidget *parent = nullptr) : QWidget(parent)
    {
        // 創(chuàng)建一個標簽
        label = new QLabel("Hello World", this);
        
        // 創(chuàng)建一個按鈕
        button = new QPushButton("獲取標簽文本", this);
        
        // 連接按鈕的點擊信號與槽函數(shù)
        connect(button, &QPushButton::clicked, this, &AnotherWindow::getLabelText);
    }
    
public slots:
    void getLabelText()
    {
        // 獲取標簽的文本值
        QString text = label->text();
        
        // 輸出文本值
        qDebug() << "標簽文本值:" << text;
    }

private:
    QLabel *label;
    QPushButton *button;
};


// 主窗口的類
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr) : QMainWindow(parent)
    {
        // 創(chuàng)建一個按鈕
        button = new QPushButton("打開另一個窗口", this);
        
        // 連接按鈕的點擊信號與槽函數(shù)
        connect(button, &QPushButton::clicked, this, &MainWindow::openAnotherWindow);
    }
    
public slots:
    void openAnotherWindow()
    {
        // 創(chuàng)建另一個窗口的實例
        AnotherWindow *anotherWindow = new AnotherWindow(this);
        
        // 顯示另一個窗口
        anotherWindow->show();
    }

private:
    QPushButton *button;
};

在上面的代碼中,主窗口類MainWindow中的openAnotherWindow函數(shù)創(chuàng)建了另一個窗口類AnotherWindow的實例anotherWindow,并顯示出來。在AnotherWindow類中,我們連接了一個按鈕的點擊信號與槽函數(shù)getLabelText。在getLabelText函數(shù)中,我們獲取了標簽label的文本值,并通過qDebug輸出到控制臺。

這樣,當我們點擊主窗口的按鈕時,會打開另一個窗口,并在另一個窗口點擊按鈕時獲取標簽的文本值并輸出到控制臺。

0