【问题标题】:How do I connect ComboBox and TextBrowser using PushButton-Qt?如何使用 PushButton-Qt 连接 ComboBox 和 TextBrowser?
【发布时间】:2019-11-26 08:03:45
【问题描述】:

我制作了一个读取文件的程序。我有一个读取行号的组合框:1,6,11,..etc。我想例如当在组合框中选择第 1 行并单击按钮时读取第 1-5 行(或在选择第 6 行时读取第 6-10 行,以此类推)。 现在我有这个。

int line_counter=1;
if(file.open (QIODevice::ReadOnly | QIODevice::Text))
{
    while(!stream.atEnd())
    {
        line = stream.readLine ();
        if(!line.isNull ())
        {
            if((line_counter%5)==1)
                ui->comboBox->addItem (line);
            line_counter++;
        }
     }
 }
 stream.flush ();
 file.close ();

void Servers::on_pushButton_clicked()
{

     if(file.open (QIODevice::ReadOnly | QIODevice::Text))
{
    for(int i=line_counter;i<line_counter+5;i++)
    {
        ui->textBrowser->setText(stream.readLine(i));
    }
}
    file.close ();

}

【问题讨论】:

  • 代码有什么问题?你试过什么?
  • @SilvanoCerza 我无法将 ComboBox 与 TextBrowser 连接。当我选择 ComboBox 中的某些项目并单击 PushButton 时,我希望程序在 TextBrowser 中显示一些特定的行。我试过: void Servers::on_pushButton_clicked() { if(file.open (QIODevice::ReadOnly | QIODevice::Text)) { for(int i=line_counter;itextBrowser- >setText(stream.readLine(i)); } } stream.flush ();文件.close(); } 但什么也没发生。
  • 请编辑问题,无法在 cmets 中格式化代码。
  • @SilvanoCerza 好的,完成。抱歉,我是 StackOverFlow 的新手。
  • 你的按钮在 ui 中是如何命名的?

标签: c++ qt combobox qcombobox qtextbrowser


【解决方案1】:

如果文本已经在comboBox 中,您可以避免从文件中读取每个要更新的团队textBrowser

首先将 pushButton 信号与您的方法连接起来:

connect(ui->pushButton, &QPushButton::clicked, this, &Servers::on_pushButton_clicked);

然后像这样更改on_pushButton_clicked

void Servers::on_pushButton_clicked()
{
    if(file.open (QIODevice::ReadOnly | QIODevice::Text))
    {
        int index = ui->comboBox->currentIndex();
        int from = 5 * index;
        int to = from + 5;
        QTextStream stream(&file);
        int lineCount = 0;
        QString text;
        QString line;
        while (stream.readLineInto(&line)) {
            if (from >= lineCount && lineCount < to) {
                text += line;
                text += '\n';
            }
            lineCount++;
        }
        ui->textBrowser->setText(text.toString());
    }
}

【讨论】:

  • 谢谢。实际上,当我将其放入代码中时,什么也没有发生。我还有一个疑问:因为我不想只阅读 ComboBox 中的行。我还想再读 4 行文件。
  • 我的错,我没有意识到 ComboBox 没有存储所有的行。我已经编辑了答案,现在应该可以了。
  • 现在它显示了所有的行。当 index 为 1 时,它显示所有 10 行,当 index 为 2 时,它还显示所有 10 行。在文本中添加一行是个好主意。但是有一个问题,因为这些线彼此相邻,我想将它们显示在另一个之下(就像在我的文件中一样)。我尝试使用 setTabPosition 但它不起作用。
  • 对,我忘了用text += '\n'; 添加换行符。现在应该没事了。
  • 感谢您的所有帮助。你启发了我解决问题。我稍微改变了一些东西,现在它正在工作。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-25
  • 2016-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多