Search code examples
c++qtqstringqprinterqstringlistmodel

How do I print QStringListModel content?


I need to print the content of a QStringListModel to a printer, in 'void MainWindow::on_pbImprime_clicked()' It's printing any Qstring with no problems, but I don't know how to put the data of QStringListModel to my QString text, anyone have an idea?

Here is my code:

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

    model = new QStringListModel(this);

    ui->lbItens->setModel(model);

    ui->lbItens->setEditTriggers(QAbstractItemView::AnyKeyPressed |
                               QAbstractItemView::DoubleClicked);
}

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

void MainWindow::on_pbAdd_clicked()
{
    int row = model->rowCount();

    model->insertRows(row,1);

    QModelIndex index = model->index(row);

    ui->lbItens->setCurrentIndex(index);
    ui->lbItens->edit(index);
}

void MainWindow::on_pbRemove_clicked()
{
    model->removeRows(ui->lbItens->currentIndex().row(),1);
}

void MainWindow::on_pbImprime_clicked()
{
        QPrinter printer;

        QPainter p(&printer);
        int x_pos = 20;
        int y_pos = 20;

        int row = model->rowCount();
        int i;

        for(i=0; i<row; i++){
            QString text = ;
            p.drawText(x_pos, y_pos, text);
            y_pos += p.fontMetrics().height();
        }
}

Sorry for my bad english and thanks for the help.


Solution

  • You can get QStringList from your model:

    QStringList list = model->stringList();
    

    From QStringList get your QString using join():

    QString str = list.join(" ");
    

    In join you may choose separator you need.