Fábio Coelho
Fábio Coelho

Reputation: 15

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.

Upvotes: 0

Views: 2264

Answers (2)

m. c.
m. c.

Reputation: 895

Alternatively, you can try this

void MainWindow::on_pbImprime_clicked()
{
    QPrinter printer;

    ...

    for(i=0; i<row; i++){
        QString text = model->data(model->index(row, 0)).toString();
        p.drawText(x_pos, y_pos, text);
        y_pos += p.fontMetrics().height();
    }
}

As a matter of fact, QVariant QAbstractItemModel::data(const QModelIndex & index, int role = Qt::DisplayRole) const is the prefered way to get data out of model.

Upvotes: 1

demonplus
demonplus

Reputation: 5801

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.

Upvotes: 1

Related Questions