首页 > 解决方案 > 如何从中央小部件类更新 MainWindow 中的状态栏?

问题描述

我一直在寻找几个小时试图找到一个小时来解决这个问题,所以我将尝试尽可能地简化它。

基本上我有一个我正在开发的赌场项目。现在我只担心二十一点,但到目前为止该程序的工作方式如下。

主窗口类

显示带有几个按钮的欢迎消息以选择您想要的游戏。单击二十一点按钮时,它将中央小部件设置为我的二十一点类。

二十一点小部件类

这是我需要帮助的地方。我想用这个类的值更新 StatusBar,但我真的无法为我的生活弄清楚如何。这是程序中的一些代码。

主窗口.cpp

void MainWindow::on_blackjackButton_clicked()
{
    Blackjack *blackjack = new Blackjack(this);
    blackjack->setPlayer(player);
    this->setCentralWidget(blackjack);
    this->setFixedSize(1600,900);
}

二十一点

void Blackjack::on_dealButton_clicked()
{

    // TODO Going to add these to the status bar
    setRegularBet(ui->spinBet->value());
    setBusterBlackjackBet(ui->spinBuster->value());
    setFortuneBet(ui->spinFortune->value());

    // Adding the 3 bets to the status bar
    QLabel *labelRegBet = new QLabel(this);
    labelRegBet->setText("Regular Bet: $" + QString::number(getRegularBet()));
}

labelRegBet 是我希望添加到状态栏的内容。

标签: c++qt

解决方案


您提出的代码对我们没有帮助,因为它对您编写的其他函数和类有太多依赖。

正如我从问题中了解到的那样,您需要一个标签statusbar of mainwindow ,您可以在标签中添加一些应该更新的内容。

所以看看这个例子,我创建了一个显示时间的标签,它每秒更新一次,我认为这会对你有所帮助,你可以在你的程序中使用它:你知道 mainwindow 默认有 statusBar 看看这个图像:

在此处输入图像描述

我在 mainwindow.cpp 中写了这个:

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

#include <QLabel>
#include <QTime>
#include <QTimer>

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

    auto    _timer = new QTimer;
    QLabel *lbl    = new QLabel(ui->statusbar);

    connect(_timer, &QTimer::timeout, this, [lbl]()
    {
        QTime time        = QTime::currentTime();
        QString Time_text = time.toString("hh : mm : ss");
        lbl->setText(Time_text);
    });

    _timer->start(1000);
}

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

输出 :

在此处输入图像描述

如您所见,我将ui->statusbar其作为标签父级。并且每秒更新一次我使用QTimer


推荐阅读