簡體   English   中英

在Qt視圖中使用QWidget

[英]Using a QWidget in a Qt View

問題:我想在視圖中顯示一個簡單的QStringListModel。 但是,我希望視圖中的每個項目都是我創建的自定義QWidget。 我不明白為什么這是一個如此困難的問題! 我已經在互聯網上尋找解決方案,盡管我發現這里和那里的點點滴滴,但沒有一個好的解決方案能滿足我的所有需求。

設置模型/視圖的基本代碼:


QStringList strings;
// add some strings to the model

QStringListModel* model = new QStringListModel(strings);
QListView* view = new QListView;

view->setModel(model);

我嘗試過這樣做的各種嘗試無濟於事。

嘗試#1

我嘗試了繼承新的QItemDelegate對象。 在這個對象中,我重寫了創建編輯器的方法。 我按照設置該委托的所有步驟進行了操作。 問題是當視圖用模型填充時,它在Qt :: DisplayRole中抓取模型中的每個項目,當我需要它來抓取Qt :: EditRole中的每個項目時。

嘗試#2

我嘗試的另一種方法是子類化QListView,並覆蓋setModel方法以為模型中的每個項調用setIndexWidget。 我的代碼看起來像這樣:


void CustomListView::setModel(QAbstractItemModel* model)
{
    QListView::setModel(model);

    for (int i = 0; i rowCount(); ++i)
    {
        QModelIndex index = model->index(i, 0);

        CustomWidget* widget = new CustomWidget;
        setIndexWidget(index, widget);
    }
}

這就像將CustomWidget對象添加到列表視圖中的每一行一樣。 為了確保常規模型數據不會顯示在我的CustomWidget對象下面,我還覆蓋了CustomListView :: paintEvent(QPaintEvent * event)什么都不做。 再次,這是有效的。

但我現在的主要問題是,當顯示列表時,雖然我的CustomWidgets正確顯示在其上,但列表的背景是純白色。 我嘗試在CustomListView上調用setAutoFillBackground(false)但沒有做任何事情。 我希望我的列表視圖具有透明背景。

appreciated. 在這個問題上的任何反饋將感激。 我花了很多時間試圖讓它發揮作用! 謝謝!

我認為我在QStandardItemModel中渲染自定義數據時遇到了類似的問題。 我解決它的方法是創建一個自定義QStyledItemDelegate。 在createEditor方法中,您可以測試:

if( qVariantCanConvert<YourObject>(index.data(Qt::YourRole)) )

然后創建您的編輯器,它實際上是您想要的自定義小部件。 並使用模型中的數據設置其值。 為了自定義我的小部件,我使用了樣式表,如CustomWidget.setStylesheet(“background:blue”);

在你的委托的paint方法中,如果你想要相同的小部件,你就像使用編輯器一樣。

CustomWidget renderer;
renderer.setText( index.data(Qt::DisplayRole).toString() );
renderer.resize(option.rect.size());
painter->save();
painter->translate(option.rect.topLeft());
renderer.render(painter);
painter->restore();

你必須自己處理openPersistentEditor和closePersistentEditor。

希望它會有所幫助。

我的建議是堅持使用自定義繪畫的代表。

請參閱Star Delegate示例如下所示,您可以根據需要繪制(見下文),然后在獲得焦點時使用createEditor進行編輯。

void StarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                          const QModelIndex &index) const
 {
     if (qVariantCanConvert<StarRating>(index.data())) {
         StarRating starRating = qVariantValue<StarRating>(index.data());

         if (option.state & QStyle::State_Selected)
             painter->fillRect(option.rect, option.palette.highlight());

         starRating.paint(painter, option.rect, option.palette,
                          StarRating::ReadOnly);
     } else {
         QStyledItemDelegate::paint(painter, option, index);
     }
 }

捕獲或作弊是您可以在不創建編輯器實例或使用drawControl()將窗口小部件置於編輯模式的情況下 drawControl()窗口小部件。 請參閱此問題中的油漆代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM