2

QStyledItemDelegate現時点では関数を再実装していないサブクラスがあります(質問を簡単にするため)。

デフォルトQStyledItemDelegateの実装では、ユーザーが でテキストの編集を開始するQTableViewと、デリゲートQLineEditはモデルからのテキストを使用して を描画し、そのすべてを選択します (編集のためにすべてを強調表示します)。

テキストは「document.pdf」などのファイル名を表します。ユーザーはこのテキスト全体を編集できますが、最初はベース名部分 (「ドキュメント」) のみを強調表示し、接尾辞 (「pdf」) は強調表示したくありません。これどうやってするの?QStyledItemDelegate(これを行う方法のロジックは必要ありません。テキストの一部を強調表示する方法を知る必要があります)

私はもう試した:

  • 一部のテキストを強調表示するためにsetEditorData()使用されます。QLineEdit::setSelection()これは効果がありません。

  • paint()他の回答者が同様の質問に推奨したものに基づいてペイントしようとしましたが、成功しませんでした。の経験はほとんどありませんQPainter。以下に例を示します: QStyledItemDelegate を使用して QStandardItem の選択動作を調整する

助けてください、そして前もって感謝します。テキストの最初の 3 文字を選択するなどのコード スニペットをいただければ幸いです。

4

1 に答える 1

4

質問への私のコメントで述べたように、サブクラスQStyledItemDelegate化とデフォルトの選択を次のsetEditorDataように設定しようとする問題:

void setEditorData(QWidget* editor, const QModelIndex &index)const{
    QStyledItemDelegate::setEditorData(editor, index);
    if(index.column() == 0){ //the column with file names in it
        //try to cast the default editor to QLineEdit
        QLineEdit* le= qobject_cast<QLineEdit*>(editor);
        if(le){
            //set default selection in the line edit
            int lastDotIndex= le->text().lastIndexOf("."); 
            le->setSelection(0,lastDotIndex);
        }
    }
}

(Qt コードで) ビューがsetEditorData hereを呼び出しselectAll() 後、エディター ウィジェットがQLineEdit. つまり、提供する選択内容はsetEditorData後で変更されます。

私が思いついた唯一の解決策は、選択をキューに入れることでした。そのため、実行がイベントループに戻ったときに選択が設定されます。これが実際の例です:

スクリーンショット

#include <QApplication>
#include <QtWidgets>

class FileNameDelegate : public QStyledItemDelegate{
public:
    explicit FileNameDelegate(QObject* parent= nullptr)
        :QStyledItemDelegate(parent){}
    ~FileNameDelegate(){}

    void setEditorData(QWidget* editor, const QModelIndex &index)const{
        QStyledItemDelegate::setEditorData(editor, index);
        //the column with file names in it
        if(index.column() == 0){
            //try to cast the default editor to QLineEdit
            QLineEdit* le= qobject_cast<QLineEdit*>(editor);
            if(le){
                QObject src;
                //the lambda function is executed using a queued connection
                connect(&src, &QObject::destroyed, le, [le](){
                    //set default selection in the line edit
                    int lastDotIndex= le->text().lastIndexOf(".");
                    le->setSelection(0,lastDotIndex);
                }, Qt::QueuedConnection);
            }
        }
    }
};

//Demo program

int main(int argc, char** argv){
    QApplication a(argc, argv);

    QStandardItemModel model;
    QList<QStandardItem*> row;
    QStandardItem item("document.pdf");
    row.append(&item);
    model.appendRow(row);
    FileNameDelegate delegate;
    QTableView tableView;
    tableView.setModel(&model);
    tableView.setItemDelegate(&delegate);
    tableView.show();

    return a.exec();
}

これはハックのように聞こえるかもしれませんが、誰かが問題に対してより良いアプローチをするまで、これを書くことにしました.

于 2016-09-24T04:46:13.043 に答える