[Qt-interest] QTableView - alignment/selection problem

Nesbitt none at none.no
Tue Dec 1 16:50:18 CET 2009


Hi

This is a repost of a problem I posted here about month ago but got no
answer (I posted this also on the Qt Centre forum and got no answer). 

I have right aligned column in QTableView (I am using AllEditTriggers).
When I click on a text in that column it selects whole text instead of
selecting it from the beginning to the place where I have clicked. 

Steps to reproduce problem:

1. Run my example program
2. Move cursor to the first cell in the right aligned column (this cell
should contain "row0col1")
3. Place mouse cursor bewteen letters "o" and "w" 
4. click

This selects whole text and text cursor is at the end of that text.
This should select only "ro" part of the text and the text cursor should
be between "o" and "w" (text cursor should be under mouse cursor).

Now do the same in left aligned column and you will see the difference.

This was tested on Linux Qt 4.5.3. 

Regards

Here is example code (main.cpp):

#include <QStandardItemModel>
#include <QItemDelegate>
#include <QLineEdit>
#include <QTableView>
#include <QApplication>

class MyDelegate: public QItemDelegate
{
public:
    MyDelegate (QObject* parent = 0):QItemDelegate(parent){}
    QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem&
option, const QModelIndex& index) const
    {
        QWidget* w = QItemDelegate::createEditor(parent, option, index);
        QLineEdit* lineEdit = qobject_cast<QLineEdit*>(w);
        if(lineEdit && index.data(Qt::TextAlignmentRole) ==
Qt::AlignRight)
            lineEdit->setAlignment(Qt::AlignRight);
        return w;
    }
};

int main(int argc,char* argv[])
{
    QApplication app(argc, argv);

    const int rowCount = 3;
    const int colCount = 2;

    QStandardItemModel* model = new QStandardItemModel(rowCount,
colCount);

    for (int row = 0; row < rowCount; ++row) {
        for (int column = 0; column < colCount; ++column) {
            QStandardItem *item = new
QStandardItem(QString("row%0col%1").arg(row).arg(column));
            model->setItem(row, column, item);
        }
        model->setData(model->index(row, 1), Qt::AlignRight,
Qt::TextAlignmentRole);
    }
    model->setHeaderData(0, Qt::Horizontal, "Left aligned",
Qt::DisplayRole);
    model->setHeaderData(1, Qt::Horizontal, "Right aligned",
Qt::DisplayRole);
    QTableView* tv = new QTableView();
    tv->resize(400, 300);
    tv->setModel(model);
    tv->setItemDelegate(new MyDelegate(tv));
    tv->setEditTriggers(QAbstractItemView::AllEditTriggers);
    
    tv->show();
    return app.exec();
}




More information about the Qt-interest-old mailing list