[Tutorial] Slate SListView Example

Hello everyone, today I wanted to create a list widget using slate . But there is not much online about this topic. There is an example of List Views on this page and ofcourse the documentation of the SListView class. The remark of that documentation is totally wrong, but luckily UE4 is open source and I found an example in the editor code. So I created a simple example class for you, so you don’t have to search for yourself!

I added a button that adds a new item to the list everytime it is pressed. You can do whatever you want to add items in a the array. Note that it doesn’t work when you add them in the Construct function.

Header:


#pragma once

#include "SlateBasics.h"

class SSomeListWidget : public SCompoundWidget
{
public:
	SLATE_BEGIN_ARGS(SSomeListWidget) {}
	SLATE_END_ARGS()

	void Construct(const FArguments& Args);
	FReply ButtonPressed();

	/* Adds a new textbox with the string to the list */
	TSharedRef<ITableRow> OnGenerateRowForList(TSharedPtr<FString> Item, const TSharedRef<STableViewBase>& OwnerTable);

	/* The list of strings */
	TArray<TSharedPtr<FString>> Items;

	/* The actual UI list */
	TSharedPtr< SListView< TSharedPtr<FString> > > ListViewWidget;
};

Source:


#include "../MultiEditPrivatePCH.h"
#include "SSomeListWidget.h"

void SSomeListWidget::Construct(const FArguments& Args)
{
	ChildSlot
		
			//Creating the button that adds a new item on the list when pressed
			SNew(SScrollBox)
			+ SScrollBox::Slot()
				
					SNew(SButton)
					.Text(FString("Add new list item"))
					.OnClicked(this, &SSomeListWidget::ButtonPressed)
				]

			//The actual list view creation
			+ SScrollBox::Slot()
				
					SAssignNew(ListViewWidget, SListView<TSharedPtr<FString>>)
					.ItemHeight(24)
					.ListItemsSource(&Items) //The Items array is the source of this listview
					.OnGenerateRow(this, &SSomeListWidget::OnGenerateRowForList)
				]
		];
}

FReply SSomeListWidget::ButtonPressed()
{
	//Adds a new item to the array (do whatever you want with this)
	Items.Add(MakeShareable(new FString("Hello 1")));

	//Update the listview
	ListViewWidget->RequestListRefresh();

	return FReply::Handled();
}


TSharedRef<ITableRow> SSomeListWidget::OnGenerateRowForList(TSharedPtr<FString> Item, const TSharedRef<STableViewBase>& OwnerTable)
{
	//Create the row
	return
		SNew(STableRow< TSharedPtr<FString> >, OwnerTable)
		.Padding(2.0f)
		
			SNew(STextBlock).Text(*Item.Get())
		];
}

Hope this can help someone! Let me know if there is anything wrong with this code, if you have feedback, or questions!

Originally posted on my blog

5 Likes

Thank you for this! Was trying to find a simple SListView Widget example but couldn’t

Hi, I was wondering is there a reason why you use TSharedPtr on the item? what if I use a simple Raw pointer instead?

It is required by the OnGenerate binding, if you use raw FString it probably won’t compile.