【问题标题】:Opening text file by using push button in Qt在 Qt 中使用按钮打开文本文件
【发布时间】:2014-04-02 11:53:23
【问题描述】:

Qt中按钮的信号和插槽区域的内容应该是什么,这样点击按钮后只会打开文本文件。

void MainWindow::on_pushButton_clicked()
 {
 ....
 }

【问题讨论】:

  • 您可以在 Qt 文档中找到有关如何读取文本文件的示例:qt-project.org/doc/qt-4.8/qfile.html
  • “打开”文本文件是什么意思?准确描述您想要发生的事情。

标签: qt signals-slots


【解决方案1】:

您可以使用任何您想要的方式来打开文件,例如 FILE、fstream、QFile ecc。您只需调用一个类方法,但在该函数中您可以放置​​所有内容。 您正在使用 Qt,因此您可以检查 QT 的 QFile 类。

【讨论】:

  • 我尝试使用 QFile file("in.txt"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) 返回; while (!file.atEnd()) { QByteArray line = file.readLine();流程线(线); } 但错误是错误的:'process_line' 没有在这个范围内声明
  • @Latik process_line() 是您必须自己编写的虚拟函数名称。将该行替换为处理文本行所需的任何内容。
【解决方案2】:

可以这样做:

void MainWindow::on_pushButton_clicked()
{

        QFile file( filename );

        if( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
            QMessageBox::warning(this, tr("Error opening!"), tr("Could not open the file"));

        QTextStream stream( &file );

        while( !stream.atEnd() )
        {
            QString lineText;
            lineText = stream.readLine(); //Read a line of text

            QStringList tokens= lineText.split(" ",QString::SkipEmptyParts); //Take tokens from the line
        }

        file.close();
}

【讨论】:

  • 我尝试使用您的代码,但它给出的警告为:Gtk-WARNING **: Failed to load type module: (null)。点击按钮后什么也没有发生。
  • 它什么都不做。它只是展示如何读取文本文件的示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2023-03-13
  • 1970-01-01
  • 2014-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多