Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何将输出写入Qt中特定标签旁边的状态栏_C++_Qt - Fatal编程技术网

C++ 如何将输出写入Qt中特定标签旁边的状态栏

C++ 如何将输出写入Qt中特定标签旁边的状态栏,c++,qt,C++,Qt,我正在Qt Creator中创建一个类似记事本的应用程序,我希望将文本统计信息写入状态栏(fe.word、字符计数)。以“单词:14个字符:80”的形式 目前,我可以通过以下方式将字数显示为int: ui->statusBar->showMessage(QString::number(counter)); 但当我想在柜台前添加一个标签“文字:”时: ui->statusBar->addPermanentWidget(ui->label1, 1); 它忽略计数器,

我正在Qt Creator中创建一个类似记事本的应用程序,我希望将文本统计信息写入状态栏(fe.word、字符计数)。以“单词:14个字符:80”的形式

目前,我可以通过以下方式将字数显示为int:

ui->statusBar->showMessage(QString::number(counter));
但当我想在柜台前添加一个标签“文字:”时:

ui->statusBar->addPermanentWidget(ui->label1, 1);
它忽略计数器,标签显示“上方”,隐藏计数器

目标是在状态栏中有4种计数器。
我目前正在寻找一个小部件,它可以让我打印一个静态字符串,比如“words:”,旁边还有一个计数器。

我没有使用QStatus栏中的小部件支持,但是你需要做的不仅仅是格式化你试图显示的字符串吗

ui->statusBar->showMessage ("words: %1 characters: %2").arg (counter).arg (char_counter);

这里有一些概念上的问题

如果将QWidget设置为QStatusBar中的永久性小部件,它通常会显示在状态栏的最右侧。临时消息(如要使用showMessage()显示的消息)将永远不会显示在其上方。通常这不是问题,因为永久小部件显示在最右侧,而临时消息显示在最左侧

关键是,您在永久标签小部件中添加了一个拉伸因子:

ui->statusBar->addPermanentWidget(ui->label1, 1);
我是说,你用“1”作为第二个参数。丢掉它。你不需要它。但您仍然不会满意您的结果,因为它看起来是这样的:

我想你想要的是这样的:

您有几个选项可以实现这一点:

  • 计数器本身就是一个自己的小部件,它被永久地添加到状态栏中,就像它后面的“Words:”标签一样
  • 例如,可以使用QString::arg()将计数器显示为单词标签的一部分
  • 创建QLabel子类,该子类显示静态文本,后跟计数器,并使用一个漂亮的setter方法更改字数。这基本上是选项2,但有点豪华
  • 也许你可以做更多的事情,但这些应该会让你走上正轨

    代码示例 1. 在每次计数更改时调用的插槽中,您可以执行以下操作:

    // Assuming that 'wordCount' contains the current word count:
    ui->label1->setText( QString( "Words: %1" ).arg( wordCount );
    
    2. 3. 在这种方法中,您实际上可以给您的WordCountIndicator,它基本上是QLabel子类的一个槽来更改文本。现在,您可以直接将其连接到一个信号,该信号在每次字数变化时都会发出(如果您有这样的事情)。如前所述,有几种方法,每种方法都有其优缺点


    注意:我没有注意到你正在“滥用”用户界面文件来创建要显示在QStatusBar中的标签。这有点不好。它仍然有效,当您将小部件设置为状态栏中的永久小部件时,它将被重新出租给QStatusBar实例。在您的情况下,我谦恭地建议您直接在代码中创建指示器标签。

    您可以调用标签上的
    setText
    label1->setText(QString(“单词:%1”).arg(123))
    
    // In your setup code:
    QLabel* wordsLabel = new QLabel( QString( "Words:" ) );
    m_wordCountLabel = new QLabel( QString::number( 0 ) ); // initial
    
    statusBar()->addPermanentWidget( wordsLabel );
    statusBar()->addPermanentWidget( m_wordCountLabel );
    
    // Inside your update word count slot:
    m_wordCountLabel->setText( QString::number( wordCount ) );
    
    // In your setup code
    m_wordCountIndicator = new MyWordCountIndicator;
    statusBar()->addPermanentWidget( m_wordCountIndicator );
    
    // Inside your update word count slot:
    m_wordCountIndicator->setWordCount( wordCount );