2016-12-29 39 views
0

我試圖做一個應用程序只是繪製幾個形狀,然後如果從三個QWidgetLists之一中選擇並單擊一個按鈕,選定的形狀將變成紅色。繪圖等是不是一個問題,但我不知道我如何檢查哪些列表是活動的,並選擇了項目。當前的代碼如下所示:如何檢查哪個QListWidget選擇了項目

QPixmap pixmap(ui->display_field->width(),ui->display_field->height()); 
    pixmap.fill("transparent"); 
    int chosen_one; 

    if(ui->radio_circle->isChecked()){ 
     if(circles_list.count() > 0){ 
      chosen_one = ui->circles_list_wgt->currentItem()->text().toInt(); 
      circles_list[chosen_one].setColor(Qt::red); 
      for(int i=0; i<circles_list.count(); i++) circles_list[i].draw(&pixmap); 
      circles_list[chosen_one].setColor(Qt::black); 
     } 

     for(int i=0; i<rectangles_list.count(); i++) rectangles_list[i].draw(&pixmap); 
     for(int i=0; i<triangles_list.count(); i++) triangles_list[i].draw(&pixmap); 
    } 

    if(ui->radio_rect->isChecked()){ 
     if(rectangles_list.count() > 0){ 
      chosen_one = ui->rectangles_list_wgt->currentItem()->text().toInt(); 
      rectangles_list[chosen_one].setColor(Qt::red); 
      for(int i=0; i<rectangles_list.count(); i++) rectangles_list[i].draw(&pixmap); 
      rectangles_list[chosen_one].setColor(Qt::black); 
     } 

     for(int i=0; i<circles_list.count(); i++) circles_list[i].draw(&pixmap); 
     for(int i=0; i<triangles_list.count(); i++) triangles_list[i].draw(&pixmap); 
    } 

    if(ui->radio_tri->isChecked()){ 
     if(triangles_list.count() > 0){ 
      chosen_one = ui->triangles_list_wgt->currentItem()->text().toInt(); 
      triangles_list[chosen_one].setColor(Qt::red); 
      for(int i=0; i<triangles_list.count(); i++) triangles_list[i].draw(&pixmap); 
      triangles_list[chosen_one].setColor(Qt::black); 
     } 

     for(int i=0; i<circles_list.count(); i++) circles_list[i].draw(&pixmap); 
     for(int i=0; i<rectangles_list.count(); i++) rectangles_list[i].draw(&pixmap); 
    } 

    ui->display_field->setPixmap(pixmap); 

原來的應用程序有工作,這取決於單選按鈕,因爲它是現在的有點不同的方法。我希望它只是項目選擇。

回答

0

兩個問題與您的解決方案:

  1. 你確實有選擇:每QListWidget都有自己的選擇,從而擁有自己的當前項目。
  2. 您應該在paintEvent中執行圖紙。

我建議如下:

  • 子類QWidget維護要繪製項的列表。
  • 實現小部件的QWidget::paintEvent方法。當需要在屏幕上繪製小部件時,此方法由Qt自動調用。您可以通過撥打QWidget::update(例如當你的形狀選擇已經改變。
  • 也許你甚至想將繪圖分解成單獨的類,如RectangleCircleTriangle類。

然後創建您的表單,其中包括三個QListWidget。創建一個插槽並將列表'QListWidget::currentRowChanged信號完全連接到此單個插槽。因此,只要您在任何列表中選擇另一個形狀,就會調用它。在插槽內部,您可以使用sender()例程來區分用戶從哪個列表中選擇一個形狀。相應地更新你的繪圖部件,請致電update,你就完成了。

相關問題