相手のウインドウにあるコントロールの値を取得する方法を教えて

別のウィンドウのウィジェットの値を取得するには、Qtのシグナルとスロットを利用できます。以下に、別のウィンドウのラベルのテキスト値を取得する方法を示すコード例を示します。

// 另一个窗口的类
class AnotherWindow : public QWidget
{
    Q_OBJECT

public:
    explicit AnotherWindow(QWidget *parent = nullptr) : QWidget(parent)
    {
        // 创建一个标签
        label = new QLabel("Hello World", this);
        
        // 创建一个按钮
        button = new QPushButton("获取标签文本", this);
        
        // 连接按钮的点击信号与槽函数
        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)
    {
        // 创建一个按钮
        button = new QPushButton("打开另一个窗口", this);
        
        // 连接按钮的点击信号与槽函数
        connect(button, &QPushButton::clicked, this, &MainWindow::openAnotherWindow);
    }
    
public slots:
    void openAnotherWindow()
    {
        // 创建另一个窗口的实例
        AnotherWindow *anotherWindow = new AnotherWindow(this);
        
        // 显示另一个窗口
        anotherWindow->show();
    }

private:
    QPushButton *button;
};

上記のコードでは、メインウィンドウクラス MainWindow の openAnotherWindow 関数は、別ウィンドウクラス AnotherWindow のインスタンス anotherWindow を作成して表示しています。AnotherWindow クラスでは、ボタンのクリックシグナルをスロット関数 getLabelText に接続しています。getLabelText 関数では、ラベル label のテキスト値を取得して、qDebug を介してコンソールに出力しています。

thus, when we click the button on the main window, another window will open, and when we click the button on another window, the text value of the label will be obtained and output to the console.

bannerAds