Item shifting using QListWidget in Qt
Article Metadata
Code Example
Tested with
Compatibility
Article
Contents |
Overview
This article demonstrates how to move items between QListWidgets. We will create an example where we will select an item from the list and then press a pushbutton to move the item to another list. If no item is selected then a messagebox appears which tells us that no item is being selected.
Basic Idea
Here the item in current selected row is removed from first list and moved to other list as well as the moved item is deleted form the first list.
Note:Please select item before moving.
How to delete item from current row
int a=ui->list2->currentRow();
delete ui->list2->takeItem(a);
Source code
Header
#include <QtGui/QWidget>
#include<QListView>
#include<QPushButton>
#include<QString>
#include<QMessageBox>
#include<QFocusEvent>
namespace Ui
{
class lisClass;
}
class lis : public QWidget
{
Q_OBJECT
public:
lis(QWidget *parent = 0);
~lis();
private:
Ui::lisClass *ui;
private slots:
void on_but2_clicked();
void on_but1_clicked();
};
#endif // LIS_H
Source File
#include "lis.h"
#include "ui_lis.h"
lis::lis(QWidget *parent)
: QWidget(parent), ui(new Ui::lisClass)
{
ui->setupUi(this);
ui->list1->addItem("Nokia N97");
ui->list1->addItem("Nokia N96");
ui->list1->addItem("Nokia N95");
ui->list1->addItem("Nokia 6630");
ui->list2->addItem("Symbian");
ui->list2->addItem("QT for S60");
ui->list2->addItem("WRT");
ui->list2->addItem("Python");
}
Method addItem() inserts an item with the text label at the end of the list widget.
lis::~lis()
{
delete ui;
}
void lis::on_but1_clicked()
{
if(ui->list1->currentItem()==0)
{
QMessageBox *msg=new QMessageBox();
msg->setText("Please select one item");
QPushButton *button=new QPushButton();
msg->addButton("ok",QMessageBox::AcceptRole);
msg->show();
ui->but1->setFocus();
}
else
{
QString str= ui->list1->currentItem()->text();
int a=ui->list1->currentRow();
delete ui->list1->takeItem(a);
ui->list2->addItem(str);
ui->but1->setFocus();
}
}
currentItem() returns the current item. Now we call currentRow() which holds the row of the current item, takeItem() removes the item from the list view. addItem()insert the item.
void lis::on_but2_clicked()
{
if(ui->list2->currentItem()==0)
{
QMessageBox *msg=new QMessageBox();
msg->setText("Please select one item");
QPushButton *button=new QPushButton();
msg->addButton("ok",QMessageBox::AcceptRole);
msg->show();
}
else
{
QString str= ui->list2->currentItem()->text();
ui->list1->addItem(str);
int a=ui->list2->currentRow();
delete ui->list2->takeItem(a);
}
}
Screenshot
apps.ui
The sample code can be found at File:Listshift.zip





(no comments yet)