【问题标题】:Qt Change label text from another classQt 从另一个类更改标签文本
【发布时间】:2017-08-10 04:57:56
【问题描述】:

我正在尝试使用 Qt 通过 B 类更改 A 类的标签文本,但我无法让它工作,这是我的代码:

A 类:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "loldata.h"

using namespace std;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    LoLData *lold = new LoLData();

    QObject::connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(updateData()));
    QObject::connect(lold, SIGNAL(updatePlayerID(QString)), ui->label, SLOT(setText(QString)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::updateData()
{
    LoLData summoner;
    summoner.getSummonerData("Snylerr");
}

A 类:(.h)

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QObject>
#include <string>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void updateData();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

B 类:

#include "loldata.h"
#include "mainwindow.h"

using namespace std;

int LoLData::getSummonerData(QString playerName)
{
    emit updatePlayerID("playerName");
    return 0;
}

B 类:(.h)

#ifndef DEF_LOLDATA
#define DEF_LOLDATA

#include <QApplication>
#include <QObject>
#include <string>

class LoLData : public QObject
{
    Q_OBJECT

public:
    int getSummonerData(QString playerName);

signals:
    void updatePlayerID(QString playerName);

private:
};

#endif

您可以看到我尝试使用插槽和信号,但标签的文本没有改变,我在互联网上看到了很多示例,但我无法让它们工作 感谢您的回复。

【问题讨论】:

    标签: c++ qt text qt-signals slots


    【解决方案1】:

    您正在此处创建LoLData 的新实例:

    void MainWindow::updateData()
    {
        LoLData summoner;
        summoner.getSummonerData("Snylerr");
    }
    

    这个名为summonerLoLData 实例未连接到您标签的setText 插槽。

    LoLData *lold = new LoLData(); - 此LolData 实例连接到您标签的setText 插槽。

    你应该怎么做? 这取决于你想完成什么:

    1. 通过插入 QObject::connect(&amp;summoner...) inside yourupdateData` 方法将您的 summoner 实例连接到标签;

    2. 或者你不实例化一个新的LolData 变量并在你的updateData 函数中使用lold

      void MainWindow::updateData() { lold->getSummonerData("Snylerr"); }

    同样在这种情况下,您必须将lold 作为成员变量。

    【讨论】:

    • 它现在可以工作了,非常感谢你,你救了我!
    【解决方案2】:

    在 MainWindow 构造函数中,将 lod 对象连接到 setText 槽。

    但是在 updateData 中,您使用了另一个对象(召唤者),它没有连接到任何东西。因此,当您在召唤器上使用 getSummonerData 时,会发出信号 updatePlayerID ,但它们没有连接到它的插槽。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多